Model Question - First Rails Project


#1

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


#2

billbell52 wrote:

problem. Here are the tables.
t.column :part_id, :integer, :null => false
‘Part’, :foreign_key => “part_parent_id”
end
Try this:

http://wiki.rubyonrails.org/rails/pages/ActsAsTree


Michael W.


#3

Bill,
I’m new to this site and typically just read everyone else’s posts,
but in this case I think I can help you with your bicycle metaphor.
I come from a manufacturing background and we construct bicycles using
a ‘Bill of Material’. This is simple a parent record for each ‘build’
build that looks like this;
BOM
PartNo_id
Quantity
(other fields if you want to get fancy)

The PartNo table obviously has
id
Descr
Qty on hand, etc.

David