Rails: Create association if none is found to avoid nil errors

前端 未结 2 1686
天涯浪人
天涯浪人 2020-12-30 06:14

I have an application where my users can have a set of preferences. Both are stored as ActiveRecord-models as follows:

class User < AR::Base
   has_one :p         


        
2条回答
  •  一向
    一向 (楼主)
    2020-12-30 06:49

    or simply

    class User < ApplicationRecord
       has_one :preference_set
    
       def preference_set
         super || build_preference_set
       end
    end
    

    This works because ActiveRecord defines the association method in a mixin.

提交回复
热议问题