I am trying to do my first Rails project. I am having a problem
understanding how to create the model. The project will track parts
that are used in building an item. It will be hierarchical. For
example a bicycle wheel is made from spokes, tire, rim and hub. A
bicycle is made up of 2 wheels. Different bicycles will use different
combinations of wheels.
I am using the book “Agile Web D. Using Rails” and the model
I have so far is below. This case is not covered in the book. Are
there any good examples of this out there. I am sure this is a common
problem. Here are the tables.
create_table :parts do |t|
t.column :name, :string, :limit => 255, :null =>
false
t.column :version, :integer, :null => false
t.column :create_date, :timestamp, :null => false
t.column :description, :text
end
create_table :uses, :id => false do |t|
t.column :part_id, :integer, :null => false
t.column :part_parent_id, :integer, :null => false
t.column :count, :integer, :null => false
end
I want to be able traverse up and down the hierarchy. Is this
close to what I need?
class Part < ActiveRecord::Base
has_many :used_by, :class_name => ‘Use’, :foreign_key => “part_id”
has_many :parents, :through => :used_by, :class_name =>
‘Part’, :foreign_key => “part_parent_id”
has_many :uses, :class_name => ‘Use’, :foreign_key =>
‘part_parent_id’
has_many :parts, :through => :uses, :class_name =>
‘Use’, :foreign_key => “part_id”
end
class Use < ActiveRecord::Base
belongs_to :parent, :class_name => ‘Part’, :source
=> :part_parent_id
belongs_to :child, :class_name => ‘Part’, :source => :part_id
end