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


i have application users can have set of preferences. both stored activerecord-models follows:

class user < ar::base    has_one :preference_set end  class preferenceset < ar::base    belongs_to :user end 

i can access preferences of user:

@u = user.first @u.preference_set => #<preferenceset...> @u.preference_set.play_sounds => true 

but fails if preference set not created, since @u.preference_set returning nil, , i'll calling play_sounds on nil.

what want archive user.preference_set returns preferenceset instance. i've tried defining this:

class user < ..    has_one :preference_set     def preference_set      preference_set || build_preference_set    end end 

this causing 'stack level deep', since calling recursively.

my question this:

how can ensure @user.preference_set returns either corresponding preference_set-record or, if none exists, builds new one?

i know rename association (eg. preference_set_real) , avoid recursive calls way, sake of simplicity in app, i'd keep naming.

thanks!

well best way create associated record when create primary one:

class user < activerecord::base    has_one       :preference_set, :autosave => true    before_create :build_preference_set end 

that set whenever user created, preferenceset. if need initialise the associated record arguments, call different method in before_create calls build_preference_set(:my_options => "here") , returns true.

you can normalise existing records iterating on don't have preferenceset , building 1 calling #create_preference_set.

if want create preferenceset when absolutely needed, can 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 

Comments

Popular posts from this blog

c++ - Convert big endian to little endian when reading from a binary file -

C#: Application without a window or taskbar item (background app) that can still use Console.WriteLine() -

unicode - Are email addresses allowed to contain non-alphanumeric characters? -