How do I run Ruby tasks that use my Rails models?

后端 未结 9 1564
醉梦人生
醉梦人生 2021-02-01 08:58

I have a Rails app with some basic models. The website displays data retrieved from other sources. So I need to write a Ruby script that creates new instances in my database. I

9条回答
  •  刺人心
    刺人心 (楼主)
    2021-02-01 09:24

    I agree with the answer above but you have to include => :environment in your task or it will not load the Rails environment.

    e.g.,

    namespace :send do
      namespace :trial do
        namespace :expiry do
          desc "Sends out emails to people who's accounts are about to expire"
          task :warnings => :environment do
            User.trial_about_to_expire.has_not_been_notified_of_trial_expiry.each do |user|
              UserMailer.deliver_trial_expiring_warning(user)
              user.notified_of_trial_expiry = true
              user.save
            end
          end
        end
      end
    end
    

提交回复
热议问题