Rails,嵌套资源,更新操作

时间:2016-02-17 18:37:18

标签: ruby-on-rails-4 form-for nested-resources

我试图通过提交表单为每个评论更新一个简单的按钮。这是我的查看代码:

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

根据上面的代码,我收到此错误:

param丢失或值为空:评论    - 错误突出显示私有声明中的params.require行

2 个答案:

答案 0 :(得分:0)

您的问题非常简单,查看您的表单,您没有任何:note因此当您尝试在params哈希中要求:note时,您会收到该错误,因为没有{ {1}}键入你的参数哈希,为了解决这个问题,你有两个选择:

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

    :note

  2. 然后在private def comment_params params.require(:comment).permit(:date, :note) end def comment_params_minimal params.require(:comment).permit(:date) end操作中有条件地使用它:

    update
    1. 另一种方法是使用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 哈希直接更新您的评论,而不是将其params列入白名单,以便以正常方式更新comment_params,仅更新if params[:comment][:note].present?直接属性:date
    2. 希望这会对你有所帮助。

答案 1 :(得分:-1)

您正在提交文章评论路径,但您的表单适用于文章(例如您的代码&lt;%= 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]

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

相关问题