編集・削除・更新時にエラーになる
コメントの登録後に編集・削除・更新をするとエラーが出てしまう。
_form.html.erbを修正した
エラー時の記述
_form.html.erb
<%= form_with model: @comment, url: diary_comments_path(@diary, comment.id), local: true do |form| %>
<div class="field">
<%= form.label :name %>
<%= form.text_field :name %>
</div>
<div class="field">
<%= form.label :content %>
<%= form.text_area :content %>
</div>
<div class="actions">
<%= form.submit %>
</div>
<% end %>
修正後
参考:[Rails 5.1] ‘form_with’ APIドキュメント完全翻訳
ルーティングが正しく設定されているdocumentにcommentを追加したい場合は次のようにする。
_form.html.erb
<%= form_with(model: [ @document, Comment.new ]) do |form| %>
...
<% end %>
日記アプリでいうと@document
は@diary
、Comment.new
はインスタンス変数にしてるので@comment
に変え、次のように修正。
_form.html.erb
<%= form_with model: [@diary, @comment], local: true do |form| %>
<div class="field">
<%= form.label :name %>
<%= form.text_field :name %>
</div>
<div class="field">
<%= form.label :content %>
<%= form.text_area :content %>
</div>
<div class="actions">
<%= form.submit %>
</div>
<% end %>