轨道上的红宝石 - 通过关系类为 2 个以上的类创建多对多关联



我正在使用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 个类的更多类。所以,可以做到这一点(也许我必须使用关联扩展类方法来达到这一点?如果是这样,我必须如何为上述示例编写代码?

您可以通过联接表使用多态关联。

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 

为了更进一步,最好通过将关联(都是相同的)移动到模块中来 DRY 它:

#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 

相关内容

  • 没有找到相关文章

最新更新