使用每当使用Rails 4 - 修改模型中的属性

时间:2014-01-31 02:42:24

标签: ruby-on-rails ruby cron whenever

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

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

任何提示?

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

谢谢!

1 个答案:

答案 0 :(得分:0)

使用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