Railsのroutes.rbにgetを指定してみる
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