【发布时间】: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