Hi there:
association.build returns unexpected behavior when returning a
reference to a unsaved parent object
class Recipe < ActiveRecord::Base
has_many :ingredients
end
class Ingredient < ActiveRecord::Base
belongs_to :recipe
end
>> r = Recipe.new
=> #<Recipe id: nil, title: nil, created_at: nil, updated_at: nil>
>> r.ingredients.build
=> #<Ingredient id: nil, name: nil, recipe_id: nil, created_at: nil, updated_at: nil>
>> r.ingredients.first.recipe
=> nil
Why nil?
>> r.save
=> true
>> r.ingredients.first.recipe
=> #<Recipe id: 3, title: nil, created_at: "2011-03-30 02:49:58", updated_at: "2011-03-30 02:49:58">
One would assume a reference to the parent object would be
returned and not nil even though the parent object has not been
saved
( It would totally make sense if recipe_id would return nil, but
recipe should be the unsaved parent object )
This picture sums up how I'm feeling right now:
