2017-01-04 55 views
0
Post has_many :comments 
Comment belongs_to :post 

我想批量更新(批准)不在cancelled帖子的所有意見。如果選擇了取消的評論,則顯示通知,否則批准評論。批量更新*職位的所有*意見,但拒絕取消

def make_comments_approved 
    comment_ids = params[:comment_ids] 

    if comment_ids 
     posts = Post.includes(:comments). 
     where(comments: { id: comment_ids.keys }) 

     comments = posts.comments 

     cancelled_comments = posts. 
     where(comments: { status: :cancelled }).comments 

     comments_to_update = comments - cancelled_comments 

     if cancelled_comments.any? 
     flash[:error] = "Cannot approve cancelled comments: #{cancelled_comments.pluck(:number)}" 
     else 
     approve_comments(comments_to_update) 
     flash[:notice] = 
      "#{pluralize(comments.count, 'comment')} successfully approved" 
     end 
    else 
     flash[:error] = 'Select comments to update' 
    end 
    redirect_to :back 
    end 

private 

    def approve_comments(comments) 
    # approve here 
    end 
+0

你好,歡迎來到SO。我回滾了你的編輯,因爲它刪除了所有問題的內容。如果您試圖刪除您的問題,則應該有一個標有「刪除」的鏈接,您可以使用該鏈接。 –

回答

0

使用update_all進行批量更新。例如:

comments.update_all(approved: true) 

但是,要小心,因爲它不會觸發驗證或回調。

0

如果你有comment_ids與你,如果你使用的是search-logic寶石做以下

cancelled_comment = Comment.where(id: comment_ids.keys, status: :cancelled) 
if cancelled_comment.count > 0 
    flash[:error] = "Cannot approve cancelled comments: #{cancelled_comments.pluck(:number)}" 
else 
    comments = Comment.where(id: comment_ids.keys).update_all() 
    flash[:notice] = "#{pluralize(comments.count, 'comment')} successfully approved" 
end 
0

,你可以做以下的(語法是軌道2)

Comment.status_ne("cancelled").update_all(:approved => true)