Running a 1 time task to enter values into database in Ruby

本秂侑毒 提交于 2019-12-23 03:06:59

问题


I have now added a new column to my table in database. I want to add some values to some rows in this new column. I know the logic and all. But actually I dont know the way to add this, or write a 1 time task to do this in ruby on rails. Can any one help me. I just need some idea.


回答1:


You can create a rake task for this, and run it once.

Create a file lib/tasks/my_namespace.rake

namespace :my_namespace do
  desc "My Task description"
  task :my_task => :environment do
    # Code to make db change goes here
  end
end

You can invoke the task from the command line in project root folder like

rake my_namespace:my_task RAILS_ENV=production




回答2:


data = Model.where(#your_condition)

if the value is same for all

data.update_all(:new_column => "new value")

if the value is different for all

data.each do |d|
  d.update_attributes(:new_column => "some value")
end


来源:https://stackoverflow.com/questions/22959356/running-a-1-time-task-to-enter-values-into-database-in-ruby

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!