【问题标题】:Using Whenever with Rails 4 - Modify attributes from a model在 Rails 4 中使用无论何时 - 从模型中修改属性
【发布时间】:2014-01-31 11:46:49
【问题描述】:

我遇到了问题。我每天都在模型类中运行一个方法(当然)。此方法遍历“假期”实例的集合,然后将这个假期的存在通知给客户端(另一个模型)。

问题来了;假期实例有一个名为“通知”的属性。我用它来知道是否已将假期通知给客户(我不想两次通知假期)。为此,我需要访问假期实例的属性以更改属性“通知”的值(布尔值)。但我不能这样做(我没有收到错误,但属性没有更新-总是错误-)

有什么提示吗?

holidays.rb

class Holiday < ActiveRecord::Base
  belongs_to :user

  def self.notify
    @holidays = Holiday.all

    @today = DateTime.now.to_date

    @holidays.each do |holiday|
      if holiday.notified == false && (holiday.fecha - @today).to_i < 15
        @clients = holiday.user.clients

        @clients.each do |client|
          ReminderMailer.new_holiday_reminder(holiday, client).deliver
        end
        holiday.notified = true <== I need to include something like this

      end
    end
  end

end

还有 scheduler.rb

every :day do
  runner "Holiday.notify", :environment => 'development'
end

谢谢!!

【问题讨论】:

    标签: ruby-on-rails ruby cron whenever


    【解决方案1】:

    使用update_attribute。此外,您不必在通知方法中使用实例变量

    class Holiday < ActiveRecord::Base
      belongs_to :user
    
      def self.notify
        holidays = Holiday.all
        today = DateTime.now.to_date
        holidays.each do |holiday|
          if holiday.notified == false && (holiday.fecha - today).to_i < 15
            clients = holiday.user.clients
            clients.each do |client|
              ReminderMailer.new_holiday_reminder(holiday, client).deliver
            end
            holiday.update_attribute(:notified, true) #or holiday.update_attributes(:notified => true)
          end
        end
      end
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多