LoginSignup
2
0

More than 5 years have passed since last update.

Rails5で複数テーブルを更新する際にform_withでハマったエラーの対策

Posted at

状況

field_forで複数テーブルに一度に保存したいけど、Unpermitted parameterとなってしまいました。

fields_forで、一度に複数のテーブルに保存したいと考えていました。フォーム内の各入力項目はブラウザ上で確認できる状態で、ページ遷移時にエラーも起こらないのですが子のテーブルにデータが保存されない状態でした。

inquiry.rb
<%= form_with scope: :inquiry, local: true do |f| %>

  <div class="field">
    <%= f.label :full_name, "名前(必須)" %>
    <%= f.text_field :full_name %>
  </div>

  <div class="field">
    <%= f.label :mail_address, "メールアドレス(必須)" %>
    <%= f.text_field :mail_address %>
  </div>

  <%= f.fields_for :inquiry_message do |mes| %>

    <div class="field">
      <%= mes.label :message, "お問い合わせ内容(必須)" %>
      <%= mes.text_area :message %>
    </div>

  <% end %>

  <div class="actions">
    <%= f.submit "確認画面へ" %>
  </div>

<% end %>

やったこと

<%= form_with scope: :inquiry, local: true do |f| %>

を下記に変更!

<%= form_with model: @inquiry, url: inquiry_path, local: true do |f| %>

理由はわからないのですが、これでエラーから抜け出せました。
もし理由がわかる方がいらっしゃいましたら、ぜひ教えてください。

自分の理解だと、scopeの場合でもmodelの場合でも、同じフォームが作成されるはずだったのですが不思議です。

もし同じようなエラーでハマった方がいらっしゃたら一度試してみてください。

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0