[英]How can i filter results in the view using includes in the controller in rails 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
@products = Product.includes(:resources).where("resources.resource_type_id = ?", @resource_type.id)
嘗試這樣的事情:
@products = Product.includes(:resources).where(resources: {
resource_type_id: @resource_type.id
})
它是最安全且更容易閱讀的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.