build association for has_one in rails

Problem

You would like to use the build method for creating an association (details) that belongs to another assocation (user).
When the user has many details then you would have something like the following:

class User < ActiveRecord::Base
  has_many :details
end

then you could do:

User.details.build

but when you have:

class User < ActiveRecord::Base
  has_one :detail
end

would throw an error:

NoMethodError: undefined method `build' ...

Solution

In order to be able to use the build in a has_one relation you would need to use like:

User.build_detail