简体   繁体   中英

Rake task failing: Environment not loading

I have the following rake task in lib/tasks/reminder_emails.rake:

namespace :tasks do
  task :send_reminder_emails => :environment do
    Registration.send_reminder_emails
  end
end

When I run bundle exec rake tasks:send_reminder_emails I set the error...

rake aborted! Expected /home/user/railsApps/nso/app/models/registration.rb to define Registration

I can run Registration.send_reminder_emails from the rails console and it works OK. Looks like maybe my environment is not loaded? However, from what I understand thats what the :environment does in the rake task.

Ideas?

Edit: Contents of app/models/registration.rb

class Registration < ActiveRecord::Base
  belongs_to :orientation
  attr_accessible :first_name, :last_name, :email, :student_id, :phone, :orientation_id, :checked_in

  validates_presence_of :first_name
  validates_presence_of :last_name
  validates_presence_of :phone
  validates_presence_of :email
  validates_format_of :email, :with => /^(|(([A-Za-z0-9]+_+)|([A-Za-z0-9]+\-+)|([A-Za-z0-9]+\.+)|([A-Za-z0-9]+\++))*[A-Za-z0-9]+@((\w+\-+)|(\w+\.))*\w{1,63}\.[a-zA-Z]{2,6})$/i
  validates_numericality_of :student_id
  validates_length_of :student_id, :minimum => 7, :maximum => 7

  def online
    self.registration.orientation != nil
  end

  def send_cancellation_email
    generate_token(:registration_cancellation_token)
    self.registration_cancelled_at = Time.zone.now
    save!
    NsoMailer.registration_cancellation_email(self).deliver
  end

  def self.send_reminder_emails
      #NsoMailer.send_reminder_emails.deliver
    registrations = Registration.where(orientation_id: Orientation.where(class_date: Date.today + 2))
    registrations.each do |r|
      NsoMailer.send_reminder_emails(r).deliver
    end
  end

  def generate_token(column)
    begin
      self[column] = SecureRandom.urlsafe_base64
    end while Registration.exists?(column => self[column])
  end
end

I found a solution that seems to work for me. I found...

Simple way of turning off observers during rake task?

I used...

Rails.configuration.active_record.observers = []

...in my rake task to disable observers. So my complete rake task now looks like...

task :send_reminder_emails => :environment do
  Rails.configuration.active_record.observers = []
  Registration.send_reminder_emails
end

...I just run bundle exec rake send_reminder_emails to run the rake task...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM