Railsのroutes.rbにgetを指定してみる

RailsでHello, world!を表示してみるの続き

root

前回、routes.rbを下記のように修正したので、

$ vi config/routes.rb
Sample::Application.routes.draw do
  root 'sample#index'
end

http://サーバーのIPアドレス/
にアクセスするとsampleコントローラのindexアクションにアクセスできる。

get

だが、下記のようにアクションが増えると、このままでは増えたアクションにアクセスできない。

$ vi app/controllers/sample_controller.rb
class SampleController < ApplicationController
  def index
    render :text => 'index'
  end
  def index2
    render :text => 'index2'
  end
  def index3
    render :text => 'index3'
  end
end

routes.rbに下記のようにgetを指定すると、アクセスできるようになる。

$ vi config/routes.rb
Sample::Application.routes.draw do
  root 'sample#index'
  get 'sample/index2' => 'sample#index2'
  get 'sample/index3' => 'sample#index3'
end

全てのgetを指定するのは面倒なので、下記のように指定すると、

$ vi config/routes.rb
Sample::Application.routes.draw do
  root 'sample#index'
  get ':controller(/:action(/:id(.:format)))'
end

http://サーバーのIPアドレス/コントローラ名/アクション名
でアクセスできる。

ネット上ではmatchを使った例が多いが、
↓を見ると4.0.0が無効になってるので、非対応になったっぽい。
match - リファレンス - Railsドキュメント
http://railsdoc.com/references/match

確認

現在のroutesの状況は下記のコマンドで確認できる。

$ rake routes
Prefix Verb URI Pattern                            Controller#Action
root GET /                                      sample#index
     GET /:controller(/:action(/:id(.:format))) :controller#:action

また、下記のURLにアクセスしても確認できる。
http://サーバーのIPアドレス/rails/info/routes