简体   繁体   中英

how to combine different controller name with other controller action? Rails

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 ?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM