#167 ✓resolved
Elliott Mason

foo.build_bar returns Foo object (belongs_to association)

Reported by Elliott Mason | February 24th, 2008 @ 06:42 PM

What the title says.

class Foo < DataMapper::Base
  belongs_to :bar

class Bar < DataMapper::Base
  has_many :foos

foo = Foo.new

will return a new Foo object. I went through the code and tracked it down to line 36 of datamapper-0.3.0\lib\data_mapper\associations\belongs_to_association.rb.

def associated_constant

@constant will return the class of the object with the association, so in this case you'd get Foo when you should get Bar. Then at like 119:

def build(options)
  @associated = association.associated_constant.new(options)

And so it's pretty obvious how things go wrong there. I ran the specs and they passed, which baffled me for another 20 minutes. They passed because

it 'can build its zoo' do
  database do |db|
    e = Exhibit.new({:name => 'Super Extra Crazy Monkey Cage'})
    e.zoo.should == nil
    e.build_zoo({:name => 'Monkey Zoo'})
    e.zoo.class == Zoo
    e.zoo.new_record?.should == true


moar like

e.zoo.class.should == Zoo

amirite? Then the tests don't pass because e.zoo would be an Exhibit.

tl;dr, I tried the following and this broke things in an unexpected way

#in datamapper-0.3.0\lib\data_mapper\associations\belongs_to_association.rb
def associated_constant

Doing this for some reason caused Bar to have a bar_id column... So I basically don't know how to fix this bug at the moment without breaking over things.

Comments and changes to this ticket

Please Sign in or create a free account to add a new ticket.

With your very own profile, you can contribute to projects, track your activity, watch tickets, receive and update tickets through your email and much more.

New-ticket Create new ticket

Create your profile

Help contribute to this project by taking a few moments to create your personal profile. Create your profile »

People watching this ticket