ruby-on-rails – 在after_initialize中Rails关联为零
发布时间:2020-12-16 19:09:20 所属栏目:百科 来源:网络整理
导读:我有两个模型,一对多关联.我想在初始化时根据父级的某些状态在子模型上设置默认值.这涉及对需要通过belongs_to关联访问父级的子进行after_initialize回调.问题是当我使用build方法实例化子进程时,after_initialize回调中与父进程的关联为nil.这是预期的行为
我有两个模型,一对多关联.我想在初始化时根据父级的某些状态在子模型上设置默认值.这涉及对需要通过belongs_to关联访问父级的子进行after_initialize回调.问题是当我使用build方法实例化子进程时,after_initialize回调中与父进程的关联为nil.这是预期的行为吗?我在rails 3.0.6上
玩具示例: class Merchant < ActiveRecord::Base has_many :products end class Product < ActiveRecord::Base belongs_to :merchant after_initialize :set_default_value def set_default_value if merchant.state self.foo = some_value else self.foo = some_other_value end end end 在控制器中: product = merchant.products.build 在对set_default_value的调用中,商家是零,虽然它似乎不应该是. 解决方法
我会改变代码如下:
class Product < ActiveRecord::Base ... def set_default_value(state = merchant.state) if state self.foo = some_value else self.foo = some_other_value end end end 然后将您的来电者更改为: product = merchant.products.build(:state => merchant.state) 另外,我发现after_initialize回调很慢.因此,另一种选择是将逻辑移动到产品的构建器中. product = merchant.products.build(:foo => merchant.state ? some_value : some_other_value) 这也消除了代码中违反Demeter的规律(即产品不应该知道/关心商家的状态). (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |