I just finished reading Josh S.'s “Self-referential has_many
:through associations” articles at:
http://blog.hasmanythrough.com/articles/2006/04/21/self-referential-through.
I’m having a little trouble trying to figure out how to do the same to
model a bill of materials. Here is the table structure I’m starting
with:
create_table :items do |t|
t.column :item_number, :string
t.column :description, :string
… and plenty more fields
end
create_table :bom_items do |t|
t.column :parent_id, :integer, :null => false
t.column :child_id, :integer, :null => false
t.column :find_number, :string
t.column :quantity, :float
t.column :notes, :string
end
I’m fairly certain the proper way to model the bom_item associations is
like this:
class BomItem < ActiveRecord::Base
belongs_to :parent, :foreign_key => “parent_id”, :class_name =>
“Item”
belongs_to :child, :foreign_key => “child_id”, :class_name =>
“Item”
end
So when I have a bom_item I can use bom_item.parent to return the
parent Item, and I can use bom_item.child to return the child Item.
That’s simple and straight forward enough. What I’m having problems
with, however, is trying to figure out how to designate the
associations on the Item model. Here is what I’d like to be able to do
on the Item model.
- call item.bom_items and retrieve a collection of BomItem objects
- call item.children and retrieve a collection of Item objects
- call item.where_used and retrieve a collection of Item objects
(basically look up the child_id in the bom_items table and return the
associated parent Item)
Now I think I have 1 and 2 figured out. Basically I’m thinking this
should work (although I haven’t tested it yet):
class Item < ActiveRecord::Base
has_many :bom_items, :foreign_key => ‘parent_id’, :class_name =>
‘Item’
has_many :children, :through => :bom_items
end
So I have two questions. Is the above the correct way to model the
associations needed for 1 and 2, and how do I model the associations
needed for number 3?
Thanks,
JB