Rails在列上嵌套资源路由

时间:2017-06-15 16:52:57

标签: ruby-on-rails ruby routing

我有一个名为Product的模型,其中有一个名为category的字段。 如何使用Product字段为category模型创建嵌套的资源丰富路由? 例如: -

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

2 个答案:

答案 0 :(得分:0)

你可能会做得很好:

resources :products do
  resources :categories
end

然后您获得new_product_category_path之类的路线助手,您可以通过/products/:id/category/:id等网址访问您的产品类别

'Rails'的做法是在product.rb中: has_many :categories。 为此,您需要在产品表中添加category_id

在category.rb中 belongs_to :product

所有这些都假定产品只有一个类别。如果没有,您必须设置一个联接表,在这种情况下,您应该查看has_manyhttp://guides.rubyonrails.org/association_basics.html#the-has-many-through-association

上的文档

答案 1 :(得分:0)

据我所知,你必须像

一样手动完成每条路线
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

为您的第一个示例/category1/params[:category]设置为控制器中的"category1"

第二个示例/category2/13

会在控制器中将params[:category]设置为"category2",将params[:id]设置为13

相关问题