Ruby on Railsで親子関係にあるモデルのルーティング設定
やりたいこと
Ruby on Railsで親子関係にあるモデルのルーティングを設定したい。
方法
route.rbにおいてモデルを下記の様にネストさせる。
$ vi config/route.rb TestApplication::Application.routes.draw do resources :animes do resources :chapters end end
ルーティング確認
$ rake routes anime_chapters GET /animes/:anime_id/chapters(.:format) chapters#index POST /animes/:anime_id/chapters(.:format) chapters#create new_anime_chapter GET /animes/:anime_id/chapters/new(.:format) chapters#new edit_anime_chapter GET /animes/:anime_id/chapters/:id/edit(.:format) chapters#edit anime_chapter GET /animes/:anime_id/chapters/:id(.:format) chapters#show PUT /animes/:anime_id/chapters/:id(.:format) chapters#update DELETE /animes/:anime_id/chapters/:id(.:format) chapters#destroy animes GET /animes(.:format) animes#index POST /animes(.:format) animes#create new_anime GET /animes/new(.:format) animes#new edit_anime GET /animes/:id/edit(.:format) animes#edit anime GET /animes/:id(.:format) animes#show PUT /animes/:id(.:format) animes#update DELETE /animes/:id(.:format) animes#destroy
View修正
- アニメ詳細画面にて各話の一覧を表示し、ツイート件数を各話詳細画面へのリンクに設定
$ vi app/views/animes/show.html.erb 下記を追記。 <% @anime.chapters.each do |chapter| %> <tr> <td><%= chapter.chapter %></td> <td><%= chapter.title %></td> <td><%= chapter.start_time %></td> <td><%= chapter.end_time %></td> <td> <%= link_to chapter.tweets.count, anime_chapter_path(@anime, chapter) %></td> </tr> <% end %>
動作確認
- ヘルパーメソッドにより生成されたリンク先を確認
正常に各話詳細画面に遷移することを確認。
<%= link_to chapter.tweets.count, anime_chapter_path(@anime, chapter) %> ↓ <a href="/animes/3/chapters/3">0</a>
参考サイト
- Rails3のルーティングについて自分なりにまとめてみる