简体   繁体   中英

Difference of update_all in Rails 3 and 4

In Rails 3.2, I have the following:

class Shop < ActiveRecord::Base
  def self.sort(shop_ids)
    shop_ids.each_with_index do |id, index|
      update_all(
        { position: index + 1 },
        id: id
      )
    end
  end
end

If I run Shop.sort([3, 1, 2]) , it will output the following query:

UPDATE `shops` SET `position` = 1 WHERE `trip_days`.`id` = 3
UPDATE `shops` SET `position` = 2 WHERE `trip_days`.`id` = 1
UPDATE `shops` SET `position` = 3 WHERE `trip_days`.`id` = 2

However when I am upgrading to Rails 4, it returns the error:

ArgumentError (wrong number of arguments (2 for 1)):

in the update_all line.

I could fix this by using .update , but it will do TWO queries per updated row. One select and one update. I don't need two queries. update_all is more straight forward.

How can I fix this?

在Rails 4,你必须做这样的

where(id: id).update_all(position: index + 1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM