新手Rails HABTM协会无法正常工作

时间:2010-07-16 00:28:36

标签: ruby-on-rails has-and-belongs-to-many

我是Rails的新手,并尝试在订单商品之间创建一个has_and_belongs_to_many关系。

class Order < ActiveRecord::Base
  has_and_belongs_to_many :items
end

class Item < ActiveRecord::Base
  has_and_belongs_to_many :orders
end

订单迁移(未显示。非常基本)

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

在脚本/控制台中,我试图“证明”这种关系有效,但要么我对Ruby的理解很糟糕(很可能),要么就是我的模型。

$ 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

查看development.sqlite3数据库:

$ 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>

什么也没有!

我知道这很明显......但不是我......在这个阶段无论如何......

我错过了什么/搞砸了什么?

1 个答案:

答案 0 :(得分:2)

首先,为什么不使用belongs_to和has_many?例如:

class Order < ActiveRecord::Base
  has_many :items
end

class Item < ActiveRecord::Base
  belongs_to :order
end

至于为什么你没有得到预期的结果,你可以尝试:

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

或更好

order = Order.create(myordercolumn => "whatever")
order.items.create(:name => "some widget")