Created
June 5, 2009 00:24
-
-
Save AlexJWayne/123966 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Relation < ActiveRecord::Base | |
belongs_to :from, :polymorphic => true | |
belongs_to :to, :polymorphic => true | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class SampleUsage < ActiveRecord::Base | |
has_relations | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I really like this implementation, it makes a lot of sense.
Where/how is this used?
self.included(receiver)
Thanks for sharing