簡體   English   中英

Rails 3和4中update_all的區別

[英]Difference of update_all in Rails 3 and 4

在Rails 3.2中,我有以下內容:

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

如果我運行Shop.sort([3, 1, 2]) ,它將輸出以下查詢:

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

但是,當我升級到Rails 4時,它返回錯誤:

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

update_all行中。

我可以通過使用.update解決這個.update ,但是每個更新的行會執行.update查詢。 一個選擇和一個更新。 我不需要兩個查詢。 update_all更直接。

我怎樣才能解決這個問題?

在Rails 4,你必須做這樣的

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM