也许菜鸟问题,也许不是,也许我缺少OOT但我仍然无法回答为什么我无法得到实例变量@upgrade的值,该值被赋予true。
class OrderTemplate < ActiveRecord::Base
belongs_to :user
attr_writer :upgrade #to hold upgrade process across actions
def upgrade
@upgrade || false
end
def from_time
p self.inspect
------------------------> they looks same
p self.upgrade
------------------------> is true as is supposed to be
p self.user.order_template.inspect
------------------------> they looks same
p self.user.order_template.upgrade
------------------------> is false but i am expecting true
self.user.has_time_bonus?
end
end
class User < ActiveRecord::Base
has_one :order_template
def has_time_bonus?
p self.order_template.upgrade
------------------------> is false but i am expecting true
end
end
请打我。
答案 0 :(得分:1)
简短版本是“activerecord没有身份地图”(或者至少,它没有启用)。如果你这样做
an_order_template.user.order_template
然后user.order_template
导致OrderTemplate
第二次从数据库加载,因此您有两个不同的内存对象代表同一个数据库行。第二个副本在内存中不会有任何更改(包括您的实例变量)。
你可以通过
来解决这个问题class OrderTemplate < ActiveRecord::Base
belongs_to :user, :inverse_of => :order_template
end
class User < ActiveRecord::Base
has_one :order_template, :inverse_of => :user
end
:inverse_of
选项可帮助Active Record加入点,以便在您执行时
an_order_template.user.order_template
rails知道两个订单模板是同一个对象。