Skip to content

Instantly share code, notes, and snippets.

@AlexJWayne
Created June 5, 2009 00:24
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save AlexJWayne/123966 to your computer and use it in GitHub Desktop.
Save AlexJWayne/123966 to your computer and use it in GitHub Desktop.
module HasRelations
module ClassMethods
def has_relations
include InstanceMethods
has_many :relations, :as => :from
end
end
module InstanceMethods
def related(relation_type = nil)
if relation_type
relations.find_all_by_to_type(relation_type.to_s.classify).map(&:to)
else
relations.map(&:to)
end
end
def add_related(model)
raise ArgumentError, "Cannot add related object since it is not an ActiveRecord model" unless model.kind_of?(ActiveRecord::Base)
relations.create(:to => model) unless related.member?(model)
model
end
end
def self.included(receiver) #:nodoc:
receiver.extend ClassMethods
end
end
ActiveRecord::Base.class_eval { include HasRelations }
class Relation < ActiveRecord::Base
belongs_to :from, :polymorphic => true
belongs_to :to, :polymorphic => true
end
class SampleUsage < ActiveRecord::Base
has_relations
end
@jDeppen
Copy link

jDeppen commented Jan 3, 2016

I really like this implementation, it makes a lot of sense.

Where/how is this used?
self.included(receiver)

Thanks for sharing

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment