Rails associations: Easy Question requires dumb answer

Scroll down to see the dumb quick question

I have two Models:

class Template < ActiveRecord::Base
end

which has this migration:
/snip
t.column :name, :string

And the other model:

class Product < ActiveRecord::Base
has_one :template
end

with the migration:
/snip

  t.column :qty, :integer, :default => 0
  t.column :specialDescription, :string
  t.column :template_id, :integer

Finally here is my controller code:

/snip
t=Product.create(:specialDescription=>“Cleans shit”,:qty=>12)
t.template=Template.find(:first)
t.save

My intention is to have several Products reference one template. But
when I execute the above snip, I get this:

Unknown column ‘templates.product_id’ in ‘where clause’: SELECT * FROM
templates WHERE (templates.product_id = 1)

Heres the dumb question:

Why didn’t that work? Obviously rails is looking in templates for a
productid, but I told it the exact opposite, that a product has a
templateid. WTF MATE???

class Template < ActiveRecord::Base
belongs_to :product
end

?

brez! !! wrote:

class Template < ActiveRecord::Base
belongs_to :product
end

?

Same error :frowning:

I am so confused

okay…

your products table has a template_id column right?

then Product belongs_to :template (the table with the *_id column is
the one that ‘belongs_to’ something else).

and you probably also want to say that Template has_many :products

Make sense?

Trevor

Trevor S.
http://somethinglearned.com

That seems so backwards… but it works.

class Template < ActiveRecord::Base
belongs_to :product
end

?

Jon wrote:

That seems so backwards… but it works.

Whoops posted too soon. I meant to Quote Trevor’s Response was the
solution that worked for the benefit of anyone else with a similar
problem

On 7/11/06, Jon [email protected] wrote:

That seems so backwards… but it works.

In your case, product belongs_to template. That means that template
has_many products.

If you have something that has_many anythings in a db schema, that table
can
not include the relationship foreign_key.

If template were to include the product_id with which it is associated,
that
template can only refer to one product at a time since there is only one
column. Conversly a product could have many templates that have it’s
product_id in the product_id column of the templates table. So in your
case you need it the other way around.

This is the way that this situation is modelled in a relational db.

In Rails, if a table includes a reference to another table, the model
for
that table, belongs_to that other model. Belongs to will look within
the
models own table for the foreign key, where has_many, and has_one will
look
in the assocated models table.

Does that make it any clearer or have I rambled a bit much? :wink: