2017-06-15 152 views
0

我有一个名为Product的模型,它有一个名为category的字段。 如何使用category字段为Product模型制作嵌套的资源路由?
如:
列上的Rails嵌套资源路由

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

我希望我的问题质量不错;新的在stackoverflow – raj1v

回答

0

你可能会被罚款这样做的:

resources :products do 
    resources :categories 
end 

然后你得到路线佣工像new_product_category_path和你的产品类别将访问一个URL像/products/:id/category/:id

的'Rails'的做法是在product.rb: has_many :categories。 对于这个工作,你在你的产品表

而且在category.rb需要category_idbelongs_to :product

这一切都假定一个产品只有一个类别。如果没有,你必须建立一个连接表,在这种情况下,你应该看看上has_many的文档通过http://guides.rubyonrails.org/association_basics.html#the-has-many-through-association

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中的控制器