【问题标题】:How can i filter results in the view using includes in the controller in rails 3?如何使用rails 3中控制器中的包含过滤视图中的结果?
【发布时间】:2011-07-26 14:02:29
【问题描述】:

我的控制器中有这个:

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

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 filter include nested-includes


    【解决方案1】:
    @products = Product.includes(:resources).where("resources.resource_type_id = ?", @resource_type.id)
    

    【讨论】:

    • 哎呀我刚刚意识到你有@products = @products.inc....(我重复了一遍)。原始的@products 变量来自哪里?试试我上面编辑的答案。
    【解决方案2】:

    试试这样的:

    @products = Product.includes(:resources).where(resources: { 
      resource_type_id: @resource_type.id 
    })
    

    它最安全,更易于阅读。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-07-11
      • 2013-08-20
      • 2013-10-20
      • 2016-11-22
      • 2014-02-10
      • 1970-01-01
      • 1970-01-01
      • 2018-09-15
      相关资源
      最近更新 更多