Lighthouse has a new layout. Prefer the old one? Return to the old layout, and switch back any time from the link at the top of each page.

This project is archived and is in readonly mode.

ActiveRecord::Associations::ClassMethods build is kind of misleading with unsaved parent objects

#6647

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:

fffffffuuuuuuuuuuuu

Reported by Anonymass · March 30th, 2011 @ 04:01 AM

State: new
Milestone: none
Assigned to: nobody
Importance: none

Activity

No comments yet.