简体   繁体   English

新手Rails HABTM关联不起作用

[英]Newbie Rails HABTM association not working

I'm new to Rails and trying to create a has_and_belongs_to_many relationship between orders and items . 我是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

Migration for Orders (not shown. very basic) 订单迁移(未显示。非常基础)

Migration for OrderItems: 迁移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. 在脚本/控制台中,我试图“证明”这种关系有效,但是我对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

looking in the development.sqlite3 database: 在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>

Nothing! 没有!

I know it's obvious...but not to me...at this stage anyway... 我知道这很明显...但是对我而言...无论如何在这个阶段...

what have I missed/screwed up? 我错过了什么?

First of all, why don't you just use belongs_to and has_many? 首先,为什么不只使用belongs_to和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")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM