Rails associations: Easy Question requires dumb answer

Scroll down to see the dumb quick question

I have two Models:

class Template < ActiveRecord::Base

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

And the other model:

class Product < ActiveRecord::Base
has_one :template

with the migration:

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

Finally here is my controller code:

t=Product.create(:specialDescription=>“Cleans shit”,:qty=>12)

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


brez! !! wrote:

class Template < ActiveRecord::Base
belongs_to :product


Same error :frowning:

I am so confused


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 S.

That seems so backwards… but it works.

class Template < ActiveRecord::Base
belongs_to :product


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

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
not include the relationship foreign_key.

If template were to include the product_id with which it is associated,
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
that table, belongs_to that other model. Belongs to will look within
models own table for the foreign key, where has_many, and has_one will
in the assocated models table.

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

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs