2016-02-10 73 views
1

我重新寫一個軌道1.x的程序,我很多年前寫的和我遇到了問題與過濾軌的ActiveRecord 4軌道4 ActiveRecord的過濾器

型號:

釉:

has_many :ingredients, dependent: :destroy 

has_many :materials, through: :ingredients 

成分:

belongs_to :glaze 

belongs_to :material 

材質:

has_many :ingredients 

has_many :glazes, through: :ingredients 

對於每種材料都有一個布爾型複選框來指示它是否爲着色劑。我想過濾每個釉面記錄不是着色劑的材料。

在我的舊鋼軌1.x的應用程序,我使用的代碼:

@batchingredients = @glaze.ingredients.find(:all, :order => 'amt DESC', :include => :material, :conditions => ['materials.colorant = ?', false]) 

我不能得到它通過傳遞非着色劑的材料。我也不確定這是否應該成爲一個工作範圍(我不是程序員,我不認爲範圍是我最後一次使用Rails的時間)。

回答

2

,所以最好在你的配料模型創建範圍:

scope :without_colorant, -> { joins(:material).where(materials: { colorant: false }) } 

那麼你的控制器是這樣的:

@batchingredients = @glaze.ingredients.without_colorant.order(amt: :desc) 
+1

想必發現材料不屬於着色劑可能是有用的其他地方。因此,可能在'Material''範圍內有一個範圍:not_colorant,{where(colorant:false)}'然後可以在任何材質上使用,並且可以在範圍內使用'scope:without_colorant, - > {joins(:material ).merge(Material.not_colorant)}' –

+0

謝謝!這很好。 – bfiess