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

后端 未结 7 657
星月不相逢
星月不相逢 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条回答
  •  情书的邮戳
    2020-12-04 06:35

    Probably not the cleanest solution, but we already had a database with half a million records, some of which already had the 'Profile' model created, and some of which didn't. We went with this approach, which guarantees a Profile model is present at any point, without needing to go through and retroactively generate all the Profile models.

    alias_method :db_profile, :profile
    def profile
      self.profile = Profile.create(:user => self) if self.db_profile.nil?
      self.db_profile
    end
    

提交回复
热议问题