Forum: Ruby on Rails Model Question - First Rails Project

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
billbell52 (Guest)
on 2007-03-13 22:48
(Received via mailing list)
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
Michael W. (Guest)
on 2007-03-13 22:52
(Received via mailing list)
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.
BraveDave (Guest)
on 2007-03-15 03:27
(Received via mailing list)
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
This topic is locked and can not be replied to.