我正在使用Ruby on Rails 3,我希望通过关系类为2个类中的更多类设置多对多关联。
例如,我有:
class RelationshipGroup < ActiveRecord::Base # This is the relationship class
# Maybe the Schema Information should be the following:
#
# Table name: RelationshipGroup
#
# id : 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
在上面的示例中,我想设置这些关联,以便可以使用RelationshipGroup
类进行搜索,以便我可以检索属于某个组的所有动物。我知道如何将has_many :through
关联用于2个类,但不能用于2个以上。因此,可以实现(可能我必须使用关联扩展或类方法来达到?)?如果是这样,我如何编写上述示例的代码?
答案 0 :(得分:1)
您可以通过连接表使用多态关联。
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
为了更进一步,通过将关联(都是相同的)移动到模块中来干掉它会很好:
#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