Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you create a migration to change data with a "where" condition in Rails 3

I have several tables loaded with data where many of the records have the field "status" set to 0. I want to change them to the value 1. Is it possible to write a migration something like this?

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

I could do it directly in MySQL but would prefer to use a migration. I've searched and experimented a bit and have not been able to find a solution that works.

Thanks for your help.

like image 918
Jay Avatar asked Jan 31 '26 16:01

Jay


1 Answers

Yes, that should be possible. Only you should use update_all instead of update:

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

(No need to use this syntax: ["status = ?", 0] when there is no user input involved)

like image 69
Mischa Avatar answered Feb 03 '26 05:02

Mischa