如何在Rails 3中使用控制器中的includes过滤视图结果?

3

我在我的控制器中有以下代码:

class User::ResourcesController < User::UserController
  def index
     @resource_type = ResourceType.find_by_name(params[:resource_type].to_s.titleize)
     @products = @products.includes(:resources).where(:resources => { :resource_type_id => @resource_type.id })

     respond_to do |format|
       format.html # index.html.erb
       format.xml  { render :xml => @resources }
     end
  end
end

我正在尝试过滤我的资源,以便在我的视图中使用下面的代码,并仅获取具有正确resource_type_id的资源。

@products.each do |product|
  product.resources.count
end
2个回答

3
@products = Product.includes(:resources).where("resources.resource_type_id = ?", @resource_type.id)

糟糕,我刚意识到你有@products = @products.inc...(而我重复了它)。原始的@products变量来自哪里?请尝试查看我上面编辑过的答案。 - Adam Albrecht

1
尝试像这样做一些事情:
@products = Product.includes(:resources).where(resources: { 
  resource_type_id: @resource_type.id 
})

它更安全且更易于阅读。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接