Rails - Best-Practice: How to create dependent has_one relations

后端 未结 7 639
星月不相逢
星月不相逢 2020-12-04 05:39

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

f.e. if i have a user model, and it must have a profile...

How could i accomplish that

7条回答
  •  -上瘾入骨i
    2020-12-04 06:15

    I had an issue with this and accepts_nested_attributes_for because if nested attributes were passed in, the associated model was created there. I ended up doing

    after_create :ensure_profile_exists
    has_one :profile
    accepts_nested_attributes_for :profile
    
    
    def ensure_profile_exists
      profile || create_profile
    end
    

提交回复
热议问题