目标是编辑相关文章的评论。Rails7.0.4.3
接收错误:
ActiveRecord::RecordNotFound in CommentsController#edit
Couldn't find Article with 'id'=#<Comment::ActiveRecord_Associations_CollectionProxy:0x00000001061950a8>
为'def edit' comments_controller.rb文件中的这一行。
我试着遵循这个nested edit path not working和ActiveRecord::RecordNotFound in Controller#edit,但没有用。
comments_controller.rb
class CommentsController < ApplicationController
def create
@article = Article.find(params[:article_id])
@comments = @article.comments.create(comment_params)
redirect_to article_path(@article)
end
def destroy
@article = Article.find(params[:article_id])
@comment = @article.comments.find(params[:id])
@comment.destroy
redirect_to article_path(@article), status: :see_other
end
def edit
@article = Article.find(params[:article_id])
@comment = @article.comments.find(params[:id])
end
def update
@article = Article.find(params[:article_id])
@comment = @article.comments.find(params[:id])
redirect_to article_path(@article)
end
private
def comment_params
params.require(:comment).permit(:commenter, :body)
end
end
_comments.html.erb
<%# unless comment.archived? %>
<p>
<strong>Commenter:</strong>
<%= comment.commenter %>
</p>
<p>
<strong>Comment:</strong>
<%= comment.body %>
</p>
<%= link_to "Edit comment", edit_article_comment_path(@article.comments) %>
<p>
<%= link_to "Destroy comment", [comment.article, comment], data: {
turbo_method: :delete,
turbo_confirm: "Are you sure?"
} %>
</p>
<%# end %>
routes.rb
Rails.application.routes.draw do
# Define your application routes per the DSL in https://guides.rubyonrails.org/routing.html
root "articles#index"
resources :articles do
resources :comments
end
end
controllers/comment.rb
class Comment < ApplicationRecord
# include Visible
belongs_to :article
end
1条答案
按热度按时间vjhs03f71#
你问题的关键在于错误本身,特别是-
这告诉你rails正在搜索一个
ID
要编辑的记录,但是你提供了一个活动记录集合,它是来自你的has_many
关联的许多记录的响应。现在看看你的
_comments.html.erb
您的路径是正确的,但是您的
edit
操作需要一个ID
,而不是您通过@article.comments
提供的注解集合。现在我建议你循环遍历你的
@article.comments
,但是看起来你已经有了<%= comment.body %>
,所以你只需要用comment
替换你的path(ID)
。一些阅读: