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???
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?
–
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.