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

后端 未结 7 618
星月不相逢
星月不相逢 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:40

    Here's how I do it. Not sure how standard this is, but it works very well and its lazy in that it doesn't create extra overhead unless it's necessary to build the new association (I'm happy to be corrected on this):

    def profile_with_auto_build
      build_profile unless profile_without_auto_build
      profile_without_auto_build
    end
    
    alias_method_chain :profile, :auto_build
    

    This also means that the association is there as soon as you need it. I guess the alternative is to hook into after_initialize but this seems to add quite a bit of overhead as it's run every time an object is initialized and there may be times where you don't care to access the association. It seems like a waste to check for its existence.

    0 讨论(0)
提交回复
热议问题