Rails: Create association if none is found to avoid nil errors
问题 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 :preference_set end class PreferenceSet < AR::Base belongs_to :user end I can now access the preferences of a user: @u = User.first @u.preference_set => #<PreferenceSet...> @u.preference_set.play_sounds => true But this fails if a preference set is not already created, since @u.preference_set will be returning nil, and I'll be calling play_sounds