2017-06-15 214 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中的控制器