How can i filter results in the view using includes in the controller in rails 3?

3k Views Asked by At

I have this in my controller:

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

I am trying to get my resources to be filtered so in my view i can use the code below and have it only pull the resources that have the correct resource_type_id.

@products.each do |product|
  product.resources.count
end
2

There are 2 best solutions below

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

Try something like this:

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

It's safest and easier to read.