2016-02-10 75 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