2016-02-17 153 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]
  • 希望這對您有所幫助。