【问题标题】:Rake task failing: Environment not loading耙任务失败:环境未加载
【发布时间】:2014-02-21 15:16:00
【问题描述】:

我在 lib/tasks/reminder_emails.rake 中有以下 rake 任务:

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

当我运行bundle exec rake tasks:send_reminder_emails 时,我设置了错误...

rake 中止! 预期 /home/user/railsApps/nso/app/models/registration.rb 来定义注册

我可以从 rails 控制台运行Registration.send_reminder_emails,它工作正常。看起来可能我的环境没有加载?但是,据我了解,这就是 :environment 在 rake 任务中的作用。

想法?

编辑: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

【问题讨论】:

  • 能把app/models/registration.rb的内容贴出来吗?
  • OK...添加了registration.rb
  • 看起来我的问题的根源是应用程序没有加载,即使我正在调用 :environment。 stackoverflow.com/questions/7044714/…
  • 嗯,看起来不错。但是,您的 self.send_reminder_emails 方法中有语法错误:您没有关闭 registrations.each 循环。
  • 我的错字...已修复。

标签: ruby-on-rails


【解决方案1】:

我找到了一个似乎对我有用的解决方案。我发现...

Simple way of turning off observers during rake task?

我用过……

Rails.configuration.active_record.observers = []

...在我的 rake 任务中禁用观察者。所以我完成的 rake 任务现在看起来像......

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

...我只是运行bundle exec rake send_reminder_emails 来运行 rake 任务...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-06-24
    • 1970-01-01
    • 2015-06-17
    • 2014-06-23
    • 2012-04-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多