导轨 - 最佳实践:如何建立相关的HAS_ONE关系导轨、关系、HAS_ONE

2023-09-08 15:56:13 作者:终丢了相思

你能告诉我什么是最好的实践创造HAS_ONE关系?

Could you tell me whats the best practice to create has_one relations?

f.e。如果我有一个用户模型,它必须有一个配置文件...

f.e. 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 doesnt seem very clean... Any suggests?

推荐答案

创建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