简体   繁体   中英

Rails nested resource route on column

I have a model named Product , which has a field named category . How do I make a nested resourceful routing for the Product model using the category field?
eg:

/category1/ --> index products with 'category = category1'
/category2/13 --> show product '13' with 'category = category2'
/categories/ --> show overview of categories

You would probably be fine doing:

resources :products do
  resources :categories
end

Then you get route helpers like new_product_category_path and your product categories would be accessible at a URL like /products/:id/category/:id

The 'Rails' way of doing it would be in product.rb: has_many :categories . For this to work you need a category_id column in your products table

And in category.rb belongs_to :product

All this assumes that a product has only one category. If not, you'll have to set up a join table, in which case you should take a look at the docs on has_many through http://guides.rubyonrails.org/association_basics.html#the-has-many-through-association

as far as I know you would have to do each route manually like

get   '/:category/',         to: "products#index"
get   '/:category/:id',      to: "products#show"
get   '/:category/new',      to: "products#new"
get   '/:category/:id/edit', to: "products#edit"
match '/:category/:id',      to: 'products#create', via: :post
match '/:category/:id',      to: 'products#update', via: [:put, :patch]
match '/:category/:id',      to: 'products#destroy', via: :delete

for your first example /category1/ will set the params[:category] to be "category1" in the controller

for your second example /category2/13 will set the params[:category] to "category2" and params[:id] to 13 in the controller

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