Reputation: 953
I want to achieve such function. So I have products controller, that handles product CRUD. And also I have categories controller, that handles category CRUD.
What I want to achieve is that when I am browsing products show action, at the browsing bar I can see such url
www.mydomainname.com/products/category_name/product_name
At this moment I have.
www.mydomainname.com/products/city-skid-7v3
So It means I need to combine 2 controllers in routes. Does somebody have example or suggestions to start with ?
Upvotes: 0
Views: 157
Reputation: 51151
You should have in your routes.rb
:
namespace :products do
resources :categories do
resources :products
end
# to index products without category:
resources :products, only: :index
end
Then you should change all places in views/controllers
where you used your routes. For example, if you have
link_to product.name, product
you should replace it with:
link_to product.name, [:products, product.category, product]
since now when linking to product, you also need to specify category url segment.
In your products#index
, you can now check if category_id
is provided and filter products respectively:
scope = if params[:category_id]
Category.find_by_permalink!(params[:category_id])
else
Product
end
@products = scope.all # add your other scopes here
Upvotes: 1