I am using Ruby on Rails 3 and I would like to set a many-to-many association for more of 2 classes through a relationship class.
For example, I have:
class RelationshipGroup < ActiveRecord::Base # This is the relationship class
# Maybe the Schema Information should be the following:
#
# Table name: RelationshipGroup
#
# id :开发者_StackOverflow中文版 integer
# dog_id: integer
# cat_id: integer
# cow_id: integer
...
end
class Dog < ActiveRecord::Base
...
end
class Cat < ActiveRecord::Base
...
end
class Cow < ActiveRecord::Base
...
end
In the above example I would like to set those associations in order to can make a search using the RelationshipGroup
class and so that I can retrieve all animals belonging to a group. I know how to use the has_many :through
association for 2 classes, but not for more of 2. So, it is possible to make that (maybe I have to use an Association Extension or a Class method to reach that?)? If so, how I must write the code for the above example?
You could use a polymorphic assocation through a join table.
class RelationshipGroup < ActiveRecord::Base # This is the relationship class
has_many :memberships
has_many :members, :through => :memberships
end
class Membership
#fields - relationship_group_id, member_id, member_type
belongs_to :relationship_group
belongs_to :member, :polymorphic => true
end
class Dog < ActiveRecord::Base
has_many :memberships, :as => :member
has_many :relationship_groups, :through => :memberships
end
class Cat < ActiveRecord::Base
has_many :memberships, :as => :member
has_many :relationship_groups, :through => :memberships
end
class Cow < ActiveRecord::Base
has_many :memberships, :as => :member
has_many :relationship_groups, :through => :memberships
end
To go a bit further, it would be good to DRY this up by moving the associations (which are all identical) into a module:
#in lib/member.rb
module Member
def self.included(base)
base.class_eval do
has_many :memberships, :as => :member
has_many :relationship_groups, :through => :memberships
end
end
end
class RelationshipGroup < ActiveRecord::Base # This is the relationship class
has_many :memberships
has_many :members, :through => :memberships
end
class Membership
#fields - relationship_group_id, member_id, member_type
belongs_to :relationship_group
belongs_to :member, :polymorphic => true
end
class Dog < ActiveRecord::Base
include Member
end
class Cat < ActiveRecord::Base
include Member
end
class Cow < ActiveRecord::Base
include Member
end
精彩评论