Unsaved record disappears when assigning to an association

Updated . Posted . Visible to the public.

If this happens to you:

user.avatar = Avatar.new
user.avatar  # => nil

(where avatar is a belongs_to), you probably declared your association incorrectly.

Always do

class User < ActiveRecord::Base
  belongs_to :avatar
end

and never

class User < ActiveRecord::Base
  belongs_to 'avatar'
end
Profile picture of Tobias Kraze
Tobias Kraze
Last edit
Henning Koch
License
Source code in this card is licensed under the MIT License.
Posted by Tobias Kraze to makandra dev (2012-09-25 12:35)