2010-11-12 203 views
1

我想爲兩個單獨但非常相似的關聯使用一個連接模型。以下是我有:Rails has_many通過過濾的關聯

兩個主要型號有:包裝,尺寸

Pacakges有多種尺寸,但有皺紋。尺寸需要分配爲頂部或底部的尺寸。我的包目前協會有:

has_many :package_sizes 
has_many :sizes, :through => :package_sizes 
has_many :bottoms_sizes, :through => :package_sizes, :scope => {:package_sizes => {:bodylocation => "B"}}, :source => :size 
has_many :tops_sizes, :through => :package_sizes, :scope => {:package_sizes => {:bodylocation => "T"}}, :source => :size 

包裝尺寸與聯接模型:size_id | package_id | bodylocation:字符串

我有一個失敗的測試,以驗證它是否工作:

@p = Package.new 
@size1 = Size.first 
@p.tops_sizes << @size1 
@p.save 
@p.reload 
@p.tops_sizes.should include(@size1) 

這應該正常工作,但由於某種原因,bodylocation場不會被自動設置。

任何想法?

回答

1

嘗試爲此創建兩個單獨的直通關聯。

has_many :bottom_package_sizes, :class_name => 'PackageSize', :conditions => {:bodylocation => 'B'} 
has_many :top_package_sizes, :class_name => 'PackageSize', :conditions => {:bodylocation => 'T'} 
has_many :bottom_sizes, :through => :bottom_package_sizes 
has_many :top_sizes, :through => :top_package_sizes 
+0

真棒。很棒。謝謝! – chrishomer 2010-11-12 02:30:34

2

有(恕我直言)較好地解決了這個在回答:Scope with join on :has_many :through association

本質上,它會是這樣的:

has_many :package_sizes 
has_many :sizes, :through => :package_sizes do 
    def tops 
    where("package_sizes.bodylocation = 'T'") 
    end 
    def bottoms 
    where("package_sizes.bodylocation = 'B'") 
    end 
end 

然後,您可以查詢他們喜歡:

@p.sizes.tops 
相關問題