Rake task to update a column value

2019-05-22 17:44发布

I am writing a rake task to update the value in a specific column in a table. When I run the task, I get this error:

uninitialized constant FirstLookSubscription

Here is the rake task code:

namespace :first_look_db do
  desc "Adds one month to the Look Subscription"
  FirstSubscription.where(subscription_state: 'active').each do |t|
        t.update_attribute :next_billing_check, '2013-9-10'

  end
end

I am new to rake tasks, and I don't want to do this as a migration. Any advice would be great!

also note: when I run this in the rails console, it executes without a problem, my biggest issue is turning it into a rake task so that our lead dev can run it

1条回答
祖国的老花朵
2楼-- · 2019-05-22 18:27

You really need a task name. The namespace gives the namespace of the task, but declare a task by name and import the environment so it can find your ActiveRecords:

namespace :first_look_db do
  desc "Adds one month to the Look Subscription"

  task :add_month_to_look_sub => :environment do
    FirstSubscription.where(subscription_state: 'active').each do |t|
      t.update_attribute :next_billing_check, '2013-9-10'

    end
  end
end

This would go into a file called lib/tasks/first_look_db.rake. The task is called by:

rake first_look_db:add_month_to_look_sub

or possibly:

bundle exec rake first_look_db:add_month_to_look_sub

If the first one tells you to do so. You can name the namespace and task however you wish in the rake file. I just picked some names that seemed to make sense to me from what you had.

查看更多
登录 后发表回答