Rails - 最佳实践:如何创建依赖 has_one 关系 [英] Rails - Best-Practice: How to create dependent has_one relations
本文介绍了Rails - 最佳实践:如何创建依赖 has_one 关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
创建 has_one 关系的最佳做法是什么?
What's the best practice to create has_one relations?
例如,如果我有一个用户模型,它必须有一个配置文件...
For example, if I have a user model, and it must have a profile...
我怎么能做到这一点?
一种解决方案是:
# user.rb
class User << ActiveRecord::Base
after_create :set_default_association
def set_default_association
self.create_profile
end
end
但这似乎不太干净......有什么建议吗?
But that doesn't seem very clean... Any suggestions?
推荐答案
创建 has_one 关系的最佳实践是使用 ActiveRecord 回调 before_create
而不是 after_create
.或者使用更早的回调并处理子进程未通过其自己的验证步骤的问题(如果有).
Best practice to create has_one relation is to use the ActiveRecord callback before_create
rather than after_create
. Or use an even earlier callback and deal with the issues (if any) of the child not passing its own validation step.
因为:
- 通过良好的编码,您有机会在验证失败时向用户显示子记录的验证
- 它更干净并且由 ActiveRecord 明确支持——AR 在保存父记录后(在创建时)会自动填充子记录中的外键.然后 AR 将子记录保存为创建父记录的一部分.
怎么做:
# in your User model...
has_one :profile
before_create :build_default_profile
private
def build_default_profile
# build default profile instance. Will use default params.
# The foreign key to the owning User model is set automatically
build_profile
true # Always return true in callbacks as the normal 'continue' state
# Assumes that the default_profile can **always** be created.
# or
# Check the validation of the profile. If it is not valid, then
# return false from the callback. Best to use a before_validation
# if doing this. View code should check the errors of the child.
# Or add the child's errors to the User model's error array of the :base
# error item
end
这篇关于Rails - 最佳实践:如何创建依赖 has_one 关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文