ruby-on-railsassociationshas-onedatabase-relations

Rails: Using build with a has_one association in rails


In this example, I create a user with no profile, then later on create a profile for that user. I tried using build with a has_one association but that blew up. The only way I see this working is using has_many. The user is supposed to only have at most one profile.

I have been trying this. I have:

class User < ActiveRecord::Base
  has_one :profile
end

class Profile < ActiveRecord::Base
  belongs_to :user
end

But when I do:

user.build_profile 

I get the error:

ActiveRecord::StatementInvalid: Mysql::Error: Unknown column 'profiles.user_id' in 'where clause': SELECT * FROM `profiles` WHERE (`profiles`.user_id = 4)  LIMIT 1

Is there a way in rails to have 0 or 1 association?


Solution

  • The build method signature is different for has_one and has_many associations.

    class User < ActiveRecord::Base
      has_one :profile
      has_many :messages
    end
    

    The build syntax for has_many association:

    user.messages.build
    

    The build syntax for has_one association:

    user.build_profile  # this will work
    
    user.profile.build  # this will throw error
    

    Read the has_one association documentation for more details.