build association for has_one in rails


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:

then you could do:

but when you have:

would throw an error:


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

Testing associations in Rspec

You would like to test your model associations in an RSpec model spec, to make sure that they are correctly set up.

After some Google searching and coming across this article here, ended up using the second method described there with the reflect_on_association method, as it doesn’t need the inclusion of another gem.
So for example to to test multiple has_many or belongs_to associations in your model rspec you could use something like:
context "check associations" do
# belongs_to associations
%w{bel_to1 bel_to2}.each do |bt|
it "should belong to #{bt}" do
m = Model.reflect_on_association(:"#{bt}")
m.macro.should == :belongs_to
# has_many associations
%w{has_many1 has_many2 has_many3}.each do |hm|
it "should have many #{hm}" do
m = Model.reflect_on_association(:"#{hm}")
m.macro.should == :has_many