您是否可以创建迁移以在Rails 3中使用“where”条件更改数据

时间:2012-04-12 03:46:26

标签: mysql ruby-on-rails-3

我有几个表加载了数据,其中许多记录的字段“status”设置为0.我想将它们更改为值1.是否可以编写这样的迁移?

class UpdateStatusContent < ActiveRecord::Migration
  def self.up
    MiscDescription.where ["status = ?", 0].update ["status = ?", 1]
    QuestionsBasic.where ["status = ?", 0].update ["status = ?", 1]
    QuestionsStrength.where ["status = ?", 0].update ["status = ?", 1]
  end

  def self.down
  end
end

我可以直接在MySQL中进行,但更喜欢使用迁移。我进行了一些搜索和实验,但未能找到有效的解决方案。

感谢您的帮助。

1 个答案:

答案 0 :(得分:2)

是的,这应该是可能的。只有您应该使用update_all而不是update

MiscDescription.where("status = 0").update_all("status = 1")

(当没有涉及用户输入时,无需使用此语法:["status = ?", 0]