chrisp
chrisp

Reputation: 2249

How do I setup a 'type' table association in Rails?

I'm sure this has been asked (and answered) in numerous locations, and it's probably that I don't know how to ask properly. Here's my issue, I'm trying to setup a simple Product to ProductType association. I'm new to RoR, and since there's so many builtin helpers in Rails I'm looking for that solution instead of normally building out everything by hand.

This is what I have for models (I'm also quite confused about how/when to use singular/plural descriptors in Rails).

product.rb

class Product< ActiveRecord::Base
 attr_accessible :name
 has_one :product_tpe
end

pruduct_type.rb

class ProductType< ActiveRecord::Base
attr_accessible :name

belongs_to :product
end

This is obviously wrong (I think I don't understand the belongs_to: method well enough). In usual SQL relationships the product table would be linked with a many to one relationship with the product_types table.

I'm getting the error:

SQLite3::SQLException: no such column: product_types.product_id: SELECT  "product_types".* FROM "product_types"  WHERE "product_types"."product_id" = 1 LIMIT 1

Since I obviously don't want a product_id in my product_types table, the error makes sense; but it's not something I did deliberately.

Not a complaint, but I've gone through the RoR guide for setting up the microposts sample app at least. Are there other excellent tutorials on working with RoR's associations?

Upvotes: 1

Views: 51

Answers (1)

Kevin Sylvestre
Kevin Sylvestre

Reputation: 38012

Your relationship is just inverted. The record with the foreign key should have the belongs_to. Also, it looks like you probably want to use a has_many relationship on the opposite end. So:

class Product < ActiveRecord::Base
  attr_accessible :name
  belongs_to :product_tpe
end

class ProductType< ActiveRecord::Base
  attr_accessible :name

  has_many :products
end

Lastly in your migration you should add in a product_type_id integer column (add an index to it as well for faster lookups).

Upvotes: 1

Related Questions