基于两个模型关联设置条件回调
Setting a conditional callback based on a two model association
我有一个 Task
属于 User
(别名为 owner
)。任务有时区,用户有时区。我不要求用户 select 在注册时输入他们的时区。因此,当他们创建任务和 select 特定形式的时区(这是必需的)时,我想采用该值并将其也保存为用户的时区。
我有一个有效的 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: Proc.new { |task| !task.owner.time_zone.present? }
我有一个 Task
属于 User
(别名为 owner
)。任务有时区,用户有时区。我不要求用户 select 在注册时输入他们的时区。因此,当他们创建任务和 select 特定形式的时区(这是必需的)时,我想采用该值并将其也保存为用户的时区。
我有一个有效的 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: Proc.new { |task| !task.owner.time_zone.present? }