验证依赖于其他模型的活动记录的模型值?
我有两个模型:
class Category < ActiveRecord::Base
has_one :weight
after_create :create_category_weight
def create_category_weight
self.weight = Weight.new :value => 1/Category.count
end
end
和..
class Weight < ActiveRecord::Base
belongs_to :category
attr_accessible :value
end
我想可靠地将值设置为(1/类别数)。我希望这能在category.build_weight、category.new、category.create等情况下工作。我已经尝试了上述方法,以及使用观察者,但它很脆弱。关于不同架构方法的建议也受到赞赏。
谢谢, 贾斯汀
I have two models:
class Category < ActiveRecord::Base
has_one :weight
after_create :create_category_weight
def create_category_weight
self.weight = Weight.new :value => 1/Category.count
end
end
and..
class Weight < ActiveRecord::Base
belongs_to :category
attr_accessible :value
end
I want to reliably set value to be (1/number of categories). I'd like this to work in the case of category.build_weight, category.new, category.create etc. I've tried the above approach, as well as using an observer, but its brittle. Suggestions on different architectural approaches also appreciated.
Thanks,
Justin
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我会将创建逻辑从 ActiveRecord 模型中提取出来并放入另一个类中。像这样的东西:
I would extract the creation logic out of the ActiveRecord model and into another class. Something like:
为什么不使用验证前回调来设置权重,并验证模型中的权重? (如果你这样做,请确保考虑竞争条件......)
Why not use a before validation callback to set the weight, and validate the weight in the model? (If you do that, make sure you take race conditions into consideration...)