Rails: Using build with a has_one association in rails

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.

Leave a Comment