【问题标题】:Rails, Nested Resource, Update ActionRails,嵌套资源,更新操作
【发布时间】:2016-02-17 18:37:18
【问题描述】:

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

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

使用上面的代码,我收到了这个错误:

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

【问题讨论】:

  • 嗨,如果我的回答有用,请考虑选择它作为接受的答案,这就是社区的运作方式......
  • 嗨,我还在等你把我的回答标记为已接受,我花了一些时间回答你...谢谢

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


【解决方案1】:

你的问题很简单,看看你的表单,你没有任何:note 所以当你尝试在你的参数哈希中要求:note 时你会得到那个错误,因为没有: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
  1. 另一种方法是直接使用params 哈希更新您的评论,而不是使用comment_params 将它们列入白名单,所以if params[:comment][:note].present? 以正常方式更新,否则,只更新date 属性直接:params[:comment][:date]

希望对你有所帮助。

【讨论】:

    【解决方案2】:

    您正在提交到文章评论路径,但您的表单是针对文章的(就像在您的代码中

    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]
    

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

    【讨论】:

      最近更新 更多