Railsのルーティングの細かいところについて
最近細かく引っかかっていたので。
URLヘルパのnew, editの修飾子は前に付く
xxxx_new_pathかnew_xxxx_pathかよく迷っていたけど、
new_xxxx_path, edit_xxxx_path
のほうが正解。namespaceで
# routes.rb namespace 'admin' do resources xxxxs end
となって、xxxxの前にadminが付くようになっても
new_admin_xxxx_path, edit_admin_xxxx_path
とnew, editが前に付く。
namespaceとscopeの作るパスとアクションの対応の違い
# routes.rb namespace 'admin' do resources xxxxs end
とすると、
コントローラのクラスのアクション | パス名 | 名前付きルーティングヘルパー |
---|---|---|
Admin::XxxxsController#index | admin/xxxxs | admin_xxxxs_path |
という風になるが、
# routes.rb scope 'admin' do resources xxxxs end
とすると、
コントローラのクラスのアクション | パス名 | 名前付きルーティングヘルパー |
---|---|---|
XxxxsController#index | admin/xxxxs | xxxxs_path |
という風に、コントローラや名前付きルーティングヘルパーはそのままでパスだけ admin
がつくようになる。
配列でのパス指定
<%= link_to 'Edit Xxxx', edit_xxxx_path(@xxxx) %>
というのを
<%= link_to 'Edit Xxxx', [:edit, @xxxx] %>
のように書ける。これは、
form_for [:admin, @article]
のように、名前空間の中に入っているパスをform_forで指定したい場合に覚えておくと便利な気がする。