Ruby on Railsで独自のルーティングとメソッドを追加したい

やりたいこと

Ruby on Railsでresourcesを使用しない独自のルーティングと、それに対応するメソッドを追加したい。

方法

route.rbにおいてmemberブロックを使用してルーティング追加
  • この例では各チャプター毎にツイートの一覧を返却する「tweets」ルーティングを追加
$ vi config/route.rb
TestApplication::Application.routes.draw do
  resources :animes do
    resources :chapters do
      member do
        get 'tweets'
      end
    end
  end
end
ルーティング確認
$ rake routes
tweets_anime_chapter GET    /animes/:anime_id/chapters/:id/tweets(.:format) chapters#tweets
      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
追加したルーティングに対応するメソッドを追加
  • 上記で確認した通り、「tweet」ルーティングに対応するメソッドは「chapters#tweets」であるため、
    Chapterコントローラーにtweetsメソッドを追加する。
$ vi app/controllers/chapters_controller.rb
  # GET /animes/1/chapters/1/tweets
  # GET /animes/1/chapters/1/tweets.json
  def tweets
    @chapter = Chapter.find(params[:id])
    @tweets = @chapter.tweets

    respond_to do |format|
      format.html
      format.json { render json: @tweets }
    end
  end

参考サイト

  • 特に無し