【发布时间】:2019-08-07 14:42:49
【问题描述】:
我通过设计、发布和评论获得用户。在显示每个帖子时,我想显示评论。
问题是我在创建评论时不断收到“多次调用渲染和/或重定向...”错误。现在,这是一个症状,而不是我想要解决的原因。调用此错误时,将突出显示 redirect_to 失败,这意味着未创建注释。
我该如何解决这个问题?此外,虽然它是次要的,但什么可以修复渲染和/或重定向...错误?
另一个细节:当我在 cmets 控制器中使用 :id 而不是 :post_id 时,它会引发错误(找不到没有 ID 的 Post)。当我在帖子控制器显示中使用 :post_id 而不是 :id 时(以提供视图表单),它会引发错误(找不到没有 ID 的帖子)
更新: 在我的comment.rb 和user.rb 中,我有belongs_to user 和has_many cmets。除了用户有很多帖子和帖子有很多 cmets。我删除了那些用户评论连接。然后我在 show.html.erb 中将@post、@comment 替换为@post、@post.cmets.build。现在它似乎保存到数据库中。但它仍然会引发“渲染和/或...”错误。我怎样才能解决这个问题?
从我的帖子列表中,我通过 post_path(post.id) 转到 show.html.erb。但是当我在 show.html.erb 中使用相同的内容时,它会显示“未定义的局部变量或方法‘post’”所以我切换到@post,然后抛出上述错误。
无论我阅读了多少文档,我都不清楚这一点。即使我没有在模型和数据库中明确表示我的用户是否连接到评论(我的评论有 post_id 但没有 user_id)?如何?
帖子控制器展示:
def show
@user = current_user
@post = Post.find(params[:id])
@comment = @post.comments.new
end
show.html.erb:
<%= form_for([@post, @comment]) do |form| %>
<p>
<%= form.text_area :text %>
</p>
<p>
<%= form.submit %>
</p>
<% end %>
完整的cmets控制器:
def show
@post = Post.find(params[:post_id])
@comment = @post.comments.new
render :template => 'posts/show'
end
def new
@post = Post.find(params[:post_id])
@comment = @post.comments.new
render :template => 'posts/show'
end
def create
@post = Post.find(params[:post_id])
@comment = @post.comments.create(comment_params)
render :template => 'posts/show'
if @comment.save
redirect_to post_path(@post), notice: "Success!~"
else
redirect_to post_path(@post), alert: "Failure!"
end
end
private
def comment_params
params.require(:comment).permit(:text)
end
路线
resources :users do
resources :posts, shallow: true do
resources :comments, shallow: true
end
end
【问题讨论】:
标签: ruby-on-rails