[英]Couldn't find [model] without an ID with has_many through association
[英]Rails has_many error - Couldn't find ID
我有評論和回復。 評論has_many回復
routes.rb
resources :comments do
resources :replies
end
當我打開評論/索引,然后選擇評論/顯示時,我會打印有關與該評論相關的所有回復的信息。
<% @comment.replies.each do |reply| %>
我也可以創建另一個回復。 所有這些都正常工作。
當我決定編輯這些答復之一時,問題就來了。
<%= link_to 'Edit', edit_comment_reply_path(@comment.replies,reply) %>
奇怪的是,如果有一個ID與我要修改的回復的ID相同的評論,則該編輯工作正常。 我要修改的特定回復甚至不必屬於該評論。 但是,如果我想編輯ID為例如66的回復,但沒有ID為66的評論,則會收到錯誤消息:
Couldn't find Comment with 'id'=65
<%=form_with(model: @reply, url: [Comment.find(params[:id]), @reply]) do |form| %>
這是replies / _form.html.erb,顯然也可以用作編輯表單。 在這種情況下,reply.id為65,它正在查找具有相同ID(不存在)的注釋。
問題出在這行代碼上。
<%= link_to 'Edit', edit_comment_reply_path(@comment.replies,reply) %>
edit_comment_reply_path
方法將@comment
作為其第一個參數。
正確的代碼應該是
<%= link_to 'Edit', edit_comment_reply_path(@comment, reply) %>
@comment
是您已在控制器edit
操作中分配了@comment
。
def edit
@comment = Comment.find(params[:comment_id])
end
要么
before_action :set_comment, only: [:create, :edit]
關鍵是您必須在視圖的正確操作中設置@comment
。
form_for
錯誤。 您可以傳入params[:id]
,它是@reply
的id
。
<%= form_with(model: @reply, url: comment_reply_path(@comment, @reply)) do |form| %>
您的控制器是什么樣的? 此外,您也不能訪問不屬於您評論的回復。 查看使用適當的作用域和授權。 我想它起作用的唯一原因是運氣。 因為您確實有一個與reply_id相匹配的comment_id,所以調用不會失敗。
好的,您還可以發布評論控制器嗎? 要點:在相關功能中使用授權(建議;假設您正在使用策略)
def edit
authorize @reply
end
如果您打算傳遞注釋ID,則還應該使用set_comment(而不僅僅是在create中)。 這樣,您還可以確保不使用不屬於您的用戶的注釋(或其他一些不想要的行為)執行回復編輯。
而且,您的問題是有關查找ID 66的問題,但錯誤提到了ID65。這僅僅是錯字嗎?
在您的RepliesController
將set comment方法更改為
def set_comment
@comment = Comment.find(reply_params[:comment_id])
end
你試過了嗎?
<%= link_to 'Edit', edit_comment_reply_path(reply) %>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.