Reputation: 1101
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?
Upvotes: 0
Views: 214
Reputation: 4643
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?
Upvotes: 1