0

I'd like to update multiple rows with update_all, but I need to use the existed value in one column selected from where(), how can I specify the value in update_all, it looks like this:

# == Schema Information
#
# Table name: records
#
#  id                 :integer          not null, primary key
#  name               :string
#  game_id            :integer
#  score              :integer
#  date               :date

Record.where(:name => "mike", :game_id => 1).update_all(score: "here I want to take out the score out and do some modifications and then store back")

Thanks a lot.

McGar
  • 205
  • 1
  • 10

2 Answers2

2

You must use SQL code to update in the manner which you want. Note that there is no way to use Ruby code to directly manipulate the score. You could create a database function if needed.

# Increment each score by a given amount
increment_amount = 10
Record.where(:name => "mike", :game_id => 1).update_all("score=score + #{increment_amount}")
Wizard of Ogz
  • 12,543
  • 2
  • 41
  • 43
  • Thanks, this seems the best way to do it now, btw, if I'd like to create a method for that, I have to extend ActiveRecord::Base to add this method there, right? – McGar Dec 03 '13 at 22:10
0

That's not really what update_all is used for. update_all generally sets the value of every instance of a certain model to one value. You could not use update_all and instead do something like

Record.where(:name => 'mike', :game_id => 1).each do |record|
  # record.score = record.score * 3 + 1
  record.save!
end

Where the comment is just an example.

kddeisz
  • 5,162
  • 3
  • 21
  • 44
  • Thanks, I know how to do it one by one, but I mean in sql we can just use "update records set score=score+2 where name='mike' and game_id=1" to update multiple rows, so there is no way to do it with active record? – McGar Dec 03 '13 at 22:02