Hey everyone… I’m just getting my feet wet with relational databases
using RoR models. The software I’m putting together relies on car
parts. Originally I had the database set up as follows
create_table :parts do |t|
t.column :year, :string
t.column :make, :string
t.column :model, :string
.
.
.
end
However, I now realize it’s much better to do it using relationships
instead. Unfortunately, I’m not too familiar with this method and
have been reading up on it for a few hours. I just want to post what
I think I’m supposed to be doing here and hopefully get a little
feedback as to whether I’m approaching this correctly before I start
programming it into my application…
class Year < ActiveRecord::Base
has_many :makes
end
class Make < ActiveRecord::Base
belongs_to :year
has_many :models, :through => something_else
end
class Model < ActiveRecord::Base
belongs_to :make
has_many :parts, :through => something
end
class Part < ActiveRecord::Base
belongs_to :model
end
However, I guess what is confusing me is that if I try to set it up
this way, if I enter a part for a 1999 Jeep Cherokee, how would I link
the part (say with part_id = 1337) to 1999, Jeep, and Cherokee? Would
I need to refine my setup here and link the part directly to the year,
make, and model by adding belongs_to and has_many or would I simply
add a column for make_id, model_id, year_id to my
“create_table :parts” method? ie:
create_table :parts do |t|
t.column :year_id
t.column :make_id
t.model :model_id
end
The other thing confusing me is the “:through => something” stuff. In
one example I see can see creating a friendship table that links two
users, but I’m not sure how I would apply it in this case or if it is
even smart to do it this way…
Any help would be appreciated. Thanks!