Skip to content

Instantly share code, notes, and snippets.

@tmarek
Forked from AlexJWayne/has_relations.rb
Created July 31, 2012 09:01
Show Gist options
  • Select an option

  • Save tmarek/3215284 to your computer and use it in GitHub Desktop.

Select an option

Save tmarek/3215284 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment