Rails4のルーティングの記述やら挙動がいまいちよくわからなかったので、ちょっと調べてみた。
ルーティングとは
config/routes.rbに記述する
URLから「どのコントローラー」の「どのアクション」に「どういうパラメータ」を与えて処理を実行するかを定義する
シンプルな例
「/tests/17 に HTTP GET すると、TestsController の hoge アクションを id=17 のパラメータで実行する」という設定。
# config/routes.rb match "/tests/:id" => "tests#hoge", as: "tests", via: "get"
こっちは「/tests/17 に HTTP POST すると、TestsController の hoge アクションを id=17 のパラメータで実行する」という設定。
# config/routes.rb match "/tests/:id" => "tests#show", as: "tests", via: "post"
上記のシンプル版
こっちが簡単で分かりやすい。
# config/routes.rb get "/tests/:id" => "tests#show", as: "tests" post "/tests/:id" => "tests#show", as: "tests"
Rails3の時のルーティング
:via
で HTTP METHOD を指定しなくてもデフォルトで HTTP GET になってたらしい。
# config/routes.rb match "/tests/:id" => "tests#show", as: "tests"
なお、Rails4では指定してあげないと以下のようなエラーが出る。
You should not use the `match` method in your router without specifying an HTTP method. If you want to expose your action to both GET and POST, add `via: [:get, :post]` option. If you want to expose your action to GET, use `get` in the router: Instead of: match "controller#action" Do: get "controller#action"