【问题标题】:Setting a conditional callback based on a two model association基于两个模型关联设置条件回调
【发布时间】:2015-07-04 14:07:58
【问题描述】:

我有一个属于User(别名为owner)的Task。一个任务有一个时区,一个用户有一个时区。我不要求用户在注册时选择他们的时区。因此,当他们创建任务并以该特定形式选择时区(这是必需的)时,我想采用该值并将其也保存为用户的时区。

我有一个有效的before_save 回调设置,但如果owner 已经有记录的时区,我不会在每次保存时调用它。我尝试设置条件但收到错误:

undefined local variable or method 'owner' for #<Class:0x007fcf7fae9510>

用户

class User < ActiveRecord::Base
  # attributes: time_zone

   has_many :owned_tasks, class_name: "Task", foreign_key: :owner_id
end

任务

class Task < ActiveRecord::Base
  # attributes: :owner_id, :time_zone

  before_save :assign_owner_time_zone if !owner.time_zone

  belongs_to :owner, class_name: "User"

  private
    def assign_owner_time_zone
      owner.update_attribute(:time_zone, time_zone)
    end
end

【问题讨论】:

  • 您在哪一行得到该错误?
  • before_save :assign_owner_time_zone if !owner.time_zone
  • 试试这个before_save :assign_owner_time_zone, if: Proc.new { |task| !task.owner.time_zone.present? }
  • 太棒了!这似乎奏效了。在你的回答中,你能否解释一下那里发生了什么?我以前没有以这种方式使用过回调。

标签: ruby-on-rails ruby activerecord callback associations


【解决方案1】:

像这样使用conditional callbacks

before_save :assign_owner_time_zone, if: Proc.new { |task| !task.owner.time_zone.present? }

【讨论】:

  • 您是否建议委托所有者的时区以避免违反得墨忒耳定律?因此,例如在 Proc 的块内:!task.owner_time_zone.present?
  • @CarlEdwards 我不能说,因为我猜它没有任何区别:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-05
  • 1970-01-01
  • 2012-05-23
相关资源
最近更新 更多