LoginSignup
24
17

More than 3 years have passed since last update.

ネストしているモデルに対するform_withの書き方

Posted at

ネストしているモデルに対するform_withの書き方

ネスト関係にある投稿記事(Postモデル)とコメント(Commentモデル)でcommentを投稿するformファイルでエラーが発生した際の対処法をまとめます。

routing
resources :posts do
     resources :comments
  end
問題のコード_form
<%= form_with(model: comment) do |form| %>

  <div class="field">
    <%= form.label :content %>
    <%= form.text_field :content %>
  </div>

  <%= form.hidden_field :post_id, value: post.id %>

  <div class="actions">
    <%= form.submit %>
  </div>
<% end %>

comments_pathというパスが見つからないというエラーが発生します。

image.png

目次

動作環境

OS : macOS Mojave 10.14.6
ruby : 2.6.3p62
rails : 5.2.4

結論

form_withにネストとされている親子関係のモデルを複数書きます。
今回のケースだとpostとcomment

_form
<%= form_with(model:[post,comment]) do |form| %>

  <div class="field">
    <%= form.label :content %>
    <%= form.text_field :content %>
  </div>

  <%= form.hidden_field :post_id, value: post.id %>

  <div class="actions">
    <%= form.submit %>
  </div>
<% end %>

このように書くことで以下のようにhtmlタグがposts/:post_id/commentsとネスト構造になります。


<form action="/posts/15/comments" accept-charset="UTF-8" data-remote="true" method="post"><input name="utf8" type="hidden" value="✓"><input type="hidden" name="authenticity_token" value="VYYDGENgBUvhCfkdZ0cISyrVi+O9nm+9/4LLwBKk4oHqE4njwC5UDXGrsCNsfYGrEOFBkfXDW+vNcasczK+yVw==">

学んだこと

今回の件で以下のことを学びました。
1. (基本)form_withのmodelには登録対象となるmodel名を入れる
コントローラーで作成したインスタンスがnewメソッドで新たに作成されて何も情報を持っていなければ自動的にcreateアクションへ、findメソッドなどで作成され、すでに情報を持っている場合はupdateアクションへ自動的に振り分けられます。
2. ネストされているルーティングの場合は親子それぞれのモデルを記述する

参考サイト

以下のサイトで詳しく解説されていました。
https://pikawaka.com/rails/form_with

24
17
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
24
17