【问题标题】:Error using `self` object in after_save callback在 after_save 回调中使用 `self` 对象时出错
【发布时间】:2013-03-22 15:33:27
【问题描述】:

我有两张表:PeopleCar

  • Person has_many cars
  • Car belongs_to person

当汽车的license_plate 发生变化时,我想向该人发送电子邮件。

我已成功创建邮件代码,但在after_save 回调中设置if 条件时遇到问题。

#Inside Person models
after_save :send_mail_notification, if: (self.cars.first.order('updated_at DESC').changed?)

def send_mail_notification(person)
    ...
end

我收到了这个错误

NoMethodError: undefined method `cars' for #<Class:0x4852ba8>

所以,我猜self 不能用于回调?有什么解决办法吗?

谢谢

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-3 conditional-statements


    【解决方案1】:
    after_save :send_mail_notification, if: Proc.new { |model| model.cars.order('updated_at DESC').first.changed? }
    

    【讨论】:

    • 现在它说NoMethodError: undefined method 'order' for #&lt;Cars:0x4bd2378&gt; 那么order 也不起作用吗?
    • 更改位置 order('updated_at DESC').first,因为 order 应该在关系上调用,而不是对象
    【解决方案2】:

    将其移入方法中?

    after_save :send_mail_notification
    
    def send_mail_notification(person)
        if (person.cars.first.order('updated_at DESC').changed?
          ..
        end
    end
    

    【讨论】:

    • 如果我把它移到方法中,我仍然需要回调来运行它。所以如果我的新回调没有if,我认为它会降低性能?
    • 感谢您的宝贵时间,我已经从上面的人那里找到了答案
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多