在尝试通过foreign_key查找对象时获取RecordNotFound异常

时间:2015-02-14 19:11:14

标签: ruby-on-rails ruby activerecord

每个都有帖子和评论表。 我正试图通过表单为每个帖子添加评论。这一切都发生在同一页面上。

查看文件代码:

<% @posts.each do |post| %>
  <%=post.title%>
  <%=post.text%>

<%post.comments.each do |com|%>
    <h3> <%=com.content%> </h3>
<%end%>

   <%= form_for post.comments.build do |f| %>
     <p>comments:</p>
     <%= f.text_area :content, size: "12x12" %>       
     <%=f.submit%>
  <% end %>
<% end %>

评论控制器代码:

def create
   @post = Post.find(params[:post_id])
   @comment = @post.comments.build(comment_params)
   @comment.save
   redirect_to root_path
end

似乎程序无法访问:post_id。 我在我的模型中有所有关联,并且:在我的数据库模式中有post_id。

Github link for this app

3 个答案:

答案 0 :(得分:1)

您需要在表单中添加<%= f.hidden_field :post_id %>,并在comment_params中允许:post_id

此外,您可能希望将创建方法代码减少到一行。

def create
    Comment.create(comment_params)
    redirect_to root_path
end

答案 1 :(得分:0)

您需要在评论控制器中允许:post_id获取强参数:

def comment_params
    params.require(:comment).permit(:content, :post_id)
end

答案 2 :(得分:0)

我发现了一个问题。 错误在于使用params [:post_id]进行搜索,而我需要在添加hidden_​​field之后通过[:comment] [:post_id]进行搜索