8
8

More than 3 years have passed since last update.

form_withで複数のモデルを渡す方法

Posted at

複数のモデルをform_withで渡す

index.html.erb
<%= form_with(model:[@post, @comment]) do |form| %>
  <%= form.text_field :content %>
  <%= form.submit %>
<% end %>

もしもここで@commentがnilとなりエラーの場合は次のようにしてもよいかもしれません。

index.html.erb
<%= form_with(model:[@post, Comment.new]) do |form| %>
  <%= form.text_field :content %>
  <%= form.submit %>
<% end %>

そもそもなぜ@commentだけではダメなの?

@commentを指定してどうして作成されないか気になるので
すこし、ソースを読んでみます。
modelを配列で渡した時は、model.lastで取得してinstantiate_builderに渡しています。

この先はのちほどしっかり読みますが、
modelを作成しているのでしょうか。
であれば...commentをcreateしてくれても良さそうな。
中途半端ですが、今後の学習のためのメモとして。

8
8
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
8
8