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?