But this does not change anythings, using
/categories/7/products always leads to the index action of the
products controller.
Is the right way to test in the index action of the products
controller whether category_id is set in params and use this
information to only show products of this category? Or is there a
better way?
should the server show me only the categories of product 7?
/categories/7/products always leads to the index action of the
products controller.
Is the right way to test in the index action of the products
controller whether category_id is set in params and use this
information to only show products of this category? Or is there a
better way?
Thanks,
HansFH
If you have a line in ProductsController#index like:
@products = Product.find(:all)
Then of course you’ll see all products. The question is what you want
to see at that url. I’d expect to see all the products in category 7
def index
if find_category @products = @category.products
else
flash[:error] = “No category with id=#{params[:category_id]}”
redirect_to categories_path
end
end
def find_category @category = Category.find_by_id(params[:category_id])
end
And you can even put the find_category into a before_filter and
redirect from it directly.
But this does not change anythings, using
/categories/7/products always leads to the index action of the
products controller.
Is the right way to test in the index action of the products
controller whether category_id is set in params and use this
information to only show products of this category? Or is there a
better way?
I am not sure if this answers your question or not, and you may know
this already, but if you have found the product with id 7 and it is in
variable @product say, then the categories for that product are
available as an array in @product.categories.
Apologies if this is nothing to do with what you want to achieve.
It sounds like your routes are set up alright, but yeah, you’ll still
need to add code so your action knows how to handle it.
In your ProductsController#index action, you probably have something
like this?
@products = Product.all
Since you have category_id in the params, something like this should
work:
if params[:category_id] @category = Category.find(params[:category_id]) @products = @category.products
end
Personally, if I have a controller that’s always used as a nested
resource, I put the initialization of the parent into a before_filter,
so it’s called for every action.
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.