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

前端 未结 2 1673
天涯浪人
天涯浪人 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.

    0 讨论(0)
  • 2020-12-30 07:15

    Well the best way to do this is to create the associated record when you create the primary one:

    class User < ActiveRecord::Base
       has_one       :preference_set, :autosave => true
       before_create :build_preference_set
    end
    

    That will set it up so whenever a User is created, so is a PreferenceSet. If you need to initialise the the associated record with arguments, then call a different method in before_create which calls build_preference_set(:my_options => "here") and then returns true.

    You can then just normalise all existing records by iterating over any that don't have a PreferenceSet and building one by calling #create_preference_set.

    If you want to only create the PreferenceSet when it is absolutely needed, then you can do something like:

    class User < ActiveRecord::Base
       has_one :preference_set
    
       def preference_set_with_initialize
         preference_set_without_initialize || build_preference_set
       end
    
       alias_method_chain :preference_set, :initialize
    end
    
    0 讨论(0)
提交回复
热议问题