views:

42

answers:

1

I'm new to Rails and trying to create a has_and_belongs_to_many relationship between orders and items.

class Order < ActiveRecord::Base
  has_and_belongs_to_many :items
end

class Item < ActiveRecord::Base
  has_and_belongs_to_many :orders
end

Migration for Orders (not shown. very basic)

Migration for OrderItems:

class CreateItems < ActiveRecord::Migration
  def self.up
    create_table :items do |t|
      t.string :name
      t.decimal :price

      t.timestamps
    end

    create_table :items_orders, :id => false do |t|
      t.references :item, :order
    end
  end

  def self.down
    drop_table :items
    drop_table :items_orders
  end
end

In script/console I'm trying to "prove" that relationship works but either my understanding of Ruby is bad (likely) or my model is.

$ script/console
Loading development environment (Rails 2.3.5)
>> o = Order.new
=> #<Order id: nil, name: nil, created_at: nil, updated_at: nil>
>> o.name = 'first order'
=> "first order"
>> o.save
=> true
>> o.items
=> []
>> i1 = o.items.new
=> #<Item id: nil, name: nil, price: nil, created_at: nil, updated_at: nil>
>> i1.name = 'some widget'
=> "some widget"
>> i1.price = 12.50
=> 12.5
>> i1.save
=> true
>> o.items
=> []
>> o.items.first
=> nil

looking in the development.sqlite3 database:

$ sqlite3 development.sqlite3 
SQLite version 3.6.12
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite> .tables
items              items_orders       orders             schema_migrations
sqlite> select * from items_orders;
sqlite> .schema items_orders
CREATE TABLE "items_orders" ("item_id" integer, "order_id" integer);
sqlite>

Nothing!

I know it's obvious...but not to me...at this stage anyway...

what have I missed/screwed up?

+2  A: 

First of all, why don't you just use belongs_to and has_many? For example:

class Order < ActiveRecord::Base
  has_many :items
end

class Item < ActiveRecord::Base
  belongs_to :order
end

As for why you don't get expected results you can try:

order = Order.new
order.save
item = Item.new
item.order = order
item.save

or better

order = Order.create(myordercolumn => "whatever")
order.items.create(:name => "some widget")
Petros
I agree with Petros (if I understand your system correctly). Also, your life will be easier if your model names match your table names -- so rename your model to ItemOrder.
John
Meltemi