列上的Rails嵌套资源路由
问题描述:
我有一个名为Product
的模型,它有一个名为category
的字段。 如何使用category
字段为Product
模型制作嵌套的资源路由?
如:
列上的Rails嵌套资源路由
/category1/ --> index products with 'category = category1'
/category2/13 --> show product '13' with 'category = category2'
/categories/ --> show overview of categories
答
你可能会被罚款这样做的:
resources :products do
resources :categories
end
然后你得到路线佣工像new_product_category_path
和你的产品类别将访问一个URL像/products/:id/category/:id
的'Rails'的做法是在product.rb: has_many :categories
。 对于这个工作,你在你的产品表
而且在category.rb需要category_id
列 belongs_to :product
这一切都假定一个产品只有一个类别。如果没有,你必须建立一个连接表,在这种情况下,你应该看看上has_many
的文档通过http://guides.rubyonrails.org/association_basics.html#the-has-many-through-association
答
据我知道你会做手工每条路线像
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中的控制器
我希望我的问题质量不错;新的在* – raj1v