こんにちは!
今回はRailsで単数リソースとform_forを使う方法についてまとめます。
単数リソースとは
- 一つだけの値を持つリソース
- 専用のモデルは持たずに、他のモデルの1レコードだけを扱うことがある
- Sessionを扱う時にも使用する
単数リソースのルーティング
resource :account
とした場合- 単数リソースなので
index
アクションはない
- 単数リソースなので
アクション | ヘルパーメソッド | パス |
---|---|---|
show | account_path, :account | /account |
new | new_account_path, :new_account | /account/new |
edit | edit_account_path, :edit_account | /account/edit |
create | account_path, :account | /account |
update | account_path, :account | /account |
destroy | account_path, :account | /account |
form_forで単数リソースを扱う場合
- 単数リソース
account
で、member
モデルのオブジェクトを更新する時
<%= form_for @member do |form| %> ... <% end %>
とすると、パラメータ名はmember
, 送信先URLは/members/123
となってしまう
<%= form_for @member, as "account", url: :account do |form| %> ... <% end %>
とすることで、パラメータ名はaccount
, 送信先URLは/account
となる
おわりに
今回は単数リソースとfrom_forについてまとめました。モデルと対応しない単数リソースはまだ使い方を掴めていない部分がありますが、使いながら慣れていきたいと思います。
50/100