How do I setup a 'type' table association in Rails? -
i'm sure has been asked (and answered) in numerous locations, , it's don't know how ask properly. here's issue, i'm trying setup simple product producttype association. i'm new ror, , since there's many builtin helpers in rails i'm looking solution instead of building out hand.
this have models (i'm quite confused how/when 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 wrong (i think don't understand belongs_to: method enough). in usual sql relationships product table linked many 1 relationship product_types table.
i'm getting error:
sqlite3::sqlexception: no such column: product_types.product_id: select "product_types".* "product_types" "product_types"."product_id" = 1 limit 1
since don't want product_id in product_types table, error makes sense; it's not did deliberately.
not complaint, i've gone through ror guide setting microposts sample app @ least. there other excellent tutorials on working ror's associations?
your relationship inverted. record foreign key should have belongs_to
. also, looks want use has_many relationship on 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 migration should add in product_type_id integer column (add index faster lookups).
Comments
Post a Comment