Search code examples
ruby-on-railsrubyupdate-all

Use Update_all with conditions


I'm trying to update all the elements of an Array, but I've this error

undefined method `update_all' for ...

@group.questions.where(user_id: current_user.id).last(@post.question_counter).update_all(post_id: @post.id)

While when I try to update_all without condition like :

@group.questions.update_all(post_id: @post.id)

The method is working. Do you have a solution to run this method ? I could do something like this to solve it, but i think is not really elegant & performant

@questions = @group.questions.where(user_id: current_user.id).last(@post.question_counter)
@questions.each do |question|
  question.update(post_id: @post.id)
end 

Solution

  • Try something like

    @group.questions.where(user_id: current_user.id).
        order('questions.id DESC').limit(@post.question_counter).
        update_all(post_id: @post.id)