批量更新*所有*评论的帖子但拒绝取消

时间:2017-01-04 09:24:51

标签: ruby-on-rails ruby ruby-on-rails-4

cancelled

我想批量更新(批准)非<{1}} 的帖子的所有评论。如果选择了已取消的评论,则显示通知,否则批准评论。

 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

3 个答案:

答案 0 :(得分:0)

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

comments.update_all(approved: true)

但是,要小心,因为它不会触发验证或回调。

答案 1 :(得分:0)

如果您有comment_ids,请执行以下操作

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

答案 2 :(得分:0)

如果您使用 search-logic gem,则可以执行以下操作(语法为Rails 2)

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