Has_many relationship question

Say I have a model called Order. Can I specify that an order “:has_many
orders” ?

That is, an order has many other orders associated with it.

I’m trying to do this, but I’m getting an error saying “undefined method
order.” Is there a join table that I need to create?

Thanks in advance.

Mariko C. wrote:

Say I have a model called Order. Can I specify that an order “:has_many
orders” ?

That is, an order has many other orders associated with it.

I’m trying to do this, but I’m getting an error saying “undefined method
order.” Is there a join table that I need to create?

Thanks in advance.

Hi Mariko C.
If you are writing code in Order model then
:has_many orders, seems to be an erronotical logic.
if you have more then one item in a single order then u have to write
has_many ordered_items
(here ordered_items is a table which linked with orders table and having
fields like id, order_id, item_id, etc.)
B’coz logically an Order doesn’t have many orders, it should be
order_items or so.
Try this, hope you will find it helpful.

Naresh.

Thank you both of you for your replies. I got it working in no time.

Mariko

Mariko C. wrote:

Say I have a model called Order. Can I specify that an order “:has_many
orders” ?

That is, an order has many other orders associated with it.

I’m trying to do this, but I’m getting an error saying “undefined method
order.” Is there a join table that I need to create?

Thanks in advance.

This is called a self-referential many-to-many relationship. Example,
using your ‘orders’, where some orders could be considered suborders of
another order.

Class Order < ActiveRecord::Base
has_and_belongs_to_many :suborders,
:class_name => “Order”,
:join_table => “suborders_orders”,
:association_foreign_key => “suborder_id”,
:foreign_key => “order_id”
end

then you can

order1main = Order.new(…)
order1suborder = Order.new(…)
order1main.suborders << order1suborder