2016-02-17 157 views
1

我试图通过提交表单来更新每个评论的简单按钮。这是我的看法代码:Rails,嵌套资源,更新操作

<% @comments.each do |comment| %> 
    <%= form_for comment, url: article_comment_path(comment.article, comment), method: :patch do |f| %> 
     <%= hidden_field_tag :update_time, Time.now %> 
     <%= f.submit "Confirm" %> 
    <% end %> 
<% end %> 

评论控制器更新操作代码:

def update 
    @article = Article.friendly.find(params[:article_id]) 
    @comment = @user.comments.find(params[:id]) 

    if @comment.update(comment_params) 
    redirect_to @comments 
    else 
    render article_comments_path(@article) 
    end 
end 

private 
     def comment_params 
      params.require(:comment).permit(:date, :note) 
     end 

通过上面的代码中,我得到这个错误:

参数是丢失或为空值:评论 - 错误突出了私人声明中的params.require行

+0

嗨,如果我的答案是有用的,请考虑选择它作为接受的答案,这就是社区的工作原理... – SsouLlesS

+0

嗨,我仍然在等待你来标记我的答案被接受,我花了一些时间回答你...谢谢 – SsouLlesS

回答

-1

您正在提交到文章评论路径,但您的表单是针对rticle(如你的代码<%= form_for文章),而不是评论。因此,您应该首先查找的参数是文章params [:article]。我想如果你把这样一个调试器

def update 
    debugger #<<<<<<<<< 
    @article = Article.friendly.find(params[:article_id]) 
    @comment = @user.comments.find(params[:id]) 

    if @comment.update(comment_params) 
    redirect_to @comments 
    else 
    render article_comments_path(@article) 
    end 
end 

然后你可以检查提交给你的控制器更新操作的参数。最有可能你会发现你的评论参数在你的文章参数像

params[:article][:comment] 

但我只是在这里猜测。通过调试器和服务器日志,您可以确切地检查提交给更新操作的参数。

+0

告诉他“调试”不是一个答案... – SsouLlesS

0

这里你的问题是非常简单的,看看你的表格,你没有任何:note所以当你尝试需要:note在PARAMS哈希那么你得到的错误,因为没有在您的PARAMS哈希:note键时,解决这个问题,你有两个选择:

  1. 创建另一个PARAMS方法和有条件地使用它:

    private def comment_params params.require(:comment).permit(:date, :note) end def comment_params_minimal params.require(:comment).permit(:date) end

,然后在update行动有条件地使用它:

def update 
    @article = Article.friendly.find(params[:article_id]) 
    @comment = @user.comments.find(params[:id]) 
    if params[:comment][:note].present? 
    use_this_params = comment_params 
    else 
    use_this_params = comment_params_minimal 
    end 
    if @comment.update(use_this_params) 
    redirect_to @comments 
    else 
    render article_comments_path(@article) 
    end 
end 
  • 另一种方式是TU直接更新使用params哈希您的评论,而不是白名单他们comment_params所以if params[:comment][:note].present?更新否则,请直接更新date属性:params[:comment][:date]
  • 希望这对您有所帮助。