【问题标题】:Getting an RecordNotFound exception when trying to find object by foreign_key尝试通过 foreign_key 查找对象时出现 RecordNotFound 异常
【发布时间】:2015-09-24 04:17:59
【问题描述】:

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

查看文件代码:

<% @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

【问题讨论】:

    标签: ruby-on-rails ruby activerecord


    【解决方案1】:

    您需要在表单中添加&lt;%= f.hidden_field :post_id %&gt; 并在comment_params 中允许:post_id

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

    def create
        Comment.create(comment_params)
        redirect_to root_path
    end
    

    【讨论】:

      【解决方案2】:

      您需要在 cmets 控制器中为您的强参数允许 :post_id

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

      【讨论】:

        【解决方案3】:

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2014-10-29
          • 2018-04-30
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-05-18
          • 1970-01-01
          相关资源
          最近更新 更多