0

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 
stig Garet
  • 564
  • 2
  • 13
  • `where(...).last(n)` returns an `Array`, whereas `where(...).limit(n)` returns an `ActiveRecord::Collection`. That's why your code fails, and the answer below works. – Tom Lord Dec 05 '17 at 14:23

1 Answers1

5

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)
Ursus
  • 29,643
  • 3
  • 33
  • 50
  • Cool exactly what I'm looking for, thanks @Ursul !! So I guess the method .last or .reverse is not working for update_all – stig Garet Dec 05 '17 at 14:17
  • Something like that. It's a method that exit from the "sql mode" let's say :) – Ursus Dec 05 '17 at 14:17
  • 2
    hey @stigGaret one thing to note when using update_all that it doesn't update the updated_at attribute incase you didn't know. (I know this is irrelevant but I found this while trying to solve your problem so I thought you should know ;D) – Joe Dec 05 '17 at 14:18
  • 1
    Because last returns an Array, not an ActiveRecord::Relation – Ursus Dec 05 '17 at 14:18