resources
RESTfulな設計を実現するために開発者自身でHTTPメソッドとURLとアクションを紐付けを行うのは手間がかかるため、
Resourcesメソッドを使い自動でRESTfulなルート定義を行う。
route.rb
resouces :name
#nameはリソース名
「name」の部分が対象のモデルのテーブルになる。
例えば
#railsコマンドでモデル作成
$ rails g model product
#routes.rbに以下の定義を追加
resources :products
#自動生成されたルートを確認
$ rails routes
rails routesコマンド
Prefix Verb URI Pattern Controller#Action
products GET /products(.:format) products#index
POST /products(.:format) products#create
new_product GET /products/new(.:format) products#new
edit_product GET /products/:id/edit(.:format) products#edit
product GET /products/:id(.:format) products#show
PATCH /products/:id(.:format) products#update
PUT /products/:id(.:format) products#update
DELETE /products/:id(.:format) products#destroy
上記のようになる。
resourcesをネストする方法
オンラインショップでの商品のレビュー情報について、
システム内部では商品のモデルとレビューのモデルが存在しており1つの商品に対して複数のレビューが存在する。
モデルクラスではそのような関連性をhas_manyやbelong_to等で表現する。
# 商品のカテゴリーの下にそれぞれreviewが存在する
/product/5/review
/product/7/review
上記のようなURL構造を設計するために、resourcesメソッドではネストによる記述を行う。
具体的にはroute.rbに下記のようなコードを追加する。
routes.rb
resources :products do
resources :reviews
end
するとrails routesは下記のようになる。
Prefix Verb URI Pattern Controller#Action
product_reviews GET /products/:product_id/reviews(.:format) reviews#index
POST /products/:product_id/reviews(.:format) reviews#create
new_product_review GET /products/:product_id/reviews/new(.:format) reviews#new
edit_product_review GET /products/:product_id/reviews/:id/edit(.:format) reviews#edit
product_review GET /products/:product_id/reviews/:id(.:format) reviews#show
PATCH /products/:product_id/reviews/:id(.:format) reviews#update
PUT /products/:product_id/reviews/:id(.:format) reviews#update
DELETE /products/:product_id/reviews/:id(.:format) reviews#destroy
products GET /products(.:format) products#index
POST /products(.:format) products#create
new_product GET /products/new(.:format) products#new
edit_product GET /products/:id/edit(.:format) products#edit
product GET /products/:id(.:format) products#show
PATCH /products/:id(.:format) products#update
PUT /products/:id(.:format) products#update
DELETE /products/:id(.:format)