2014-03-25 304 views
0

我想要3種模型:訂單,產品,屬性。每個訂單都可以有很多屬性。每個產品都可以有很多屬性,當然訂單可以有很多產品。這裏是我的模型:多對多關係

class Order < ActiveRecord::Base 
    belongs_to :customer 

    has_and_belongs_to_many :products 
    has_and_belongs_to_many :attributes 
    has_one :invoice_address, class_name: 'OrderAddress' 
    has_one :delivery_address, class_name: 'OrderAddress' 

    validates :number, presence: true 
    validates :total_amount, presence: true 
end 

product.rb

class Product < ActiveRecord::Base 
    has_and_belongs_to_many :orders 
    has_and_belongs_to_many :attributes 
end 

和attribute.rb

class Attribute < ActiveRecord::Base 
    has_and_belongs_to_many :orders 
    has_and_belongs_to_many :products 
end 

基於我對這個職位http://jonathanhui.com/ruby-rails-3-model-many-many-association的問題我的代碼,當我想創造新的訂購:

dev_customer = Customer.create(:name => 'dev') 

dev_user = dev_customer.users.create(:email => '[email protected]', :password => 'bk020488', :password_confirmation => 'bk020488') 

first_order = dev_customer.orders.create(:number => 1, :total_amount => 555, :paid_amount => 555) 

first_order.products.create(:name => 'First product', :price => 111, :qty => 1) 
first_order.products.create(:name => 'Second product', :price => 222, :qty => 2) 

它打破了第5行與消息

未定義的方法'鍵爲#

我該怎麼辦錯了嗎?

回答

0

dev_customer.users返回一個用戶數組。這不是你想要的。

在這種情況下,你應該進入這樣的事情:

first_order = Order.create(:customer_id => dev_customer.id, :number => 1, :total_amount => 555, :paid_amount => 555) 

這回答您的主要問題。

你可能想看看其他幾個要素:

  • 在大多數情況下,多對多協會,的has_many:通過模式是最好
  • 您的訂單,並應計算其總金額直接從產品
  • 支付的金額可能來自'支付'模型中的記錄
  • 爲了語義上正確,產品應描述產品,您現在稱爲產品的產品應該是購物卡產品。

無論如何,玩得開心。