简体   繁体   English

Rails在列上嵌套资源路由

[英]Rails nested resource route on column

I have a model named Product , which has a field named category . 我有一个名为Product的模型,该模型具有一个名为category的字段。 How do I make a nested resourceful routing for the Product model using the category field? 如何使用category字段为Product模型进行嵌套的资源丰富的路由?
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 然后,您将获得诸如new_product_category_path类的路线助手,并且可以通过/products/:id/category/:id的URL访问您的产品类别

The 'Rails' way of doing it would be in product.rb: has_many :categories . “ Rails”的实现方式将在product.rb: has_many :categories For this to work you need a category_id column in your products table 为此,您需要在产品表中的category_id

And in category.rb belongs_to :product 并且在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 如果不是,则必须设置一个联接表,在这种情况下,您应该通过http://guides.rubyonrails.org/association_basics.html#the-has-many-through-查看has_many上的文档。 协会

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 对于您的第一个示例/category1/将在控制器中将params[:category]设置为"category1"

for your second example /category2/13 will set the params[:category] to "category2" and params[:id] to 13 in the controller 对于第二个示例, /category2/13将在控制器中将params[:category]"category2"并将params[:id]为13

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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