0

In Rails / Activerecord I have changed a field to make it required; I want to run

AppVersion.where('content_rating IS NULL').each {|av| av.update_column('content_rating', 7) }

to ensure that content_rating is not null.

From what I read, Migrations are not a good place to actually change records. Is there a "do this once" way to run code within the Rails structure?

Dave Edelhart
  • 1,051
  • 1
  • 9
  • 13

1 Answers1

1

Yes, you can create a rake task:

http://railsguides.net/2012/03/14/how-to-generate-rake-task/

$ rails g task update_version update_rating_column
$ create lib/tasks/update_version.rake

namespace :update_version do
  desc "Update content_rating"
  task :update_rating_column => :environment do
    AppVersion.where('content_rating IS NULL').each {|av| av.update_column('content_rating', 7) }
  end
end

You can run the task in the migration if needed:

Execute a Rake task from within migration?

Community
  • 1
  • 1
Jorge de los Santos
  • 4,583
  • 1
  • 17
  • 35