はじめに
この記事はTwitterで人気のハッシュタグ#100DaysOfCode
をつけて、
100日間プログラミング学習を続けるチャレンジに挑戦した17日目の記録です。
動作環境
- ruby 2.4.1
- Rails 5.0.1
現在学習している内容のリポジトリ
本日学んだこと
- has_manyとroutesの関係
- has_oneとroutesの関係
has_manyとroutesの関係
belongs_toと同様に、has_manyの関係においても親子関係をネストさせてroutesで表現することができます。
ただし、belongs_toやhas_oneと違うのは、単一リソースでも表記が複数形になるという点。
例:Contactモデルからみて、Phoneモデルはhas_manyの関係にある
Rails.application.routes.draw do
resources :contacts do
# Phoneモデルとのネストされたroutes(has_many)
resource :phones, only: [:show]
resource :phones, only: [:show], path: 'relationships/phones'
end
end
上記のコードによって、下記のようなルーティングが生成されます。
Helper | HTTP/Verb | Path | Controller#Action |
---|---|---|---|
contact_phones_path | GET | /contacts/:contact_id/phones(.:format) | phones#show |
GET | /contacts/:contact_id/relationships/phones(.:format) | phones#show |
has_oneとroutesの関係
has_oneもbelongs_toやhas_manyと同様に、親子関係をネストさせてroutesで表現することができます。
has_oneはその名の通り、Contactモデルに対して紐付くオブジェクトが1つだけなので、belongs_to同様にシンボルで渡すモデル名は単数形です。
例:Contactモデルからみて、Phoneモデルはhas_manyの関係にある
Rails.application.routes.draw do
resources :contacts do
# Addressモデルとのネストされたroutes(has_one)
resource :address, only: [:show]
resource :address, only: [:show], path: 'relationships/address'
end
end
上記のコードによって、下記のようなルーティングが生成されます。
Helper | HTTP/Verb | Path | Controller#Action |
---|---|---|---|
contact_address_path | GET | /contacts/:contact_id/address(.:format) | addresses#show |
GET | /contacts/:contact_id/relationships/address(.:format) | addresses#show |
※controller名は必ず複数形にする命名規則があるので、addressesとなっています。