1

我有機型導軌的has_many:通過使用協會和中間協會

class Product < ActiveRecord::Base 
    has_many :product_tags 
    has_many :tags, :through => :product_tags, :source => tag 
end 

class ProductTag < ActiveRecord::Base 
    belongs_to :product 
    belongs_to :tag 
end 

class Tag < ActiveRecord::Base 
    has_many :product_tags  
    has_many :products, :through => :product_tags, :source => :tag 

    has_many :tag_group_tags 
    has_many :tag_groups, :through => :tag_group_tags, :source => :tag_group 
end 

class TagGroupTag < ActiveRecord::Base 
    belongs_to :tag 
    belongs_to :tag_group 
end 

class TagGroup < ActiveRecord::Base 
    has_many :tag_group_tags 
    has_many :tags, :through => :tag_group_tags 
end 

我想定義上TagGroup協會,會給我,那其間唯一Product「被分配給所有Tag S」這TagGroup

比方說,我有:

product1 
product2 
tag1 
tag2 
tag_group1 

與以下關聯S:

product1.tags << tag1 

product2.tags << tag1 
product2.tags << tag2 

tag_group1.tags << tag1 
tag_group1.tags << tag2 

當我做tag_group1.products我想只得到product2因爲product2被分配給兩個tag1tag2

product1不應該返回,因爲它只是分配給tag1

任何想法怎麼辦呢?

回答

0

我不知道,但你可以嘗試類似如下:

class TagGroup < ActiveRecord::Base 
    has_many :tag_group_tags 
    has_many :tags, :through => :tag_group_tags 
    has_many :products, :conditions => ['tags = ?', self.tags] 
end