很多关系

时间:2014-03-25 07:19:23

标签: activerecord ruby-on-rails-4 rails-models

我想要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 => 'test@test.pl', :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行打破了消息

  

未定义的方法`键&#39;对于#

我做错了什么?

1 个答案:

答案 0 :(得分:0)

dev_customer.users返回一组用户。这不是你想要的。

在这种情况下,您应该输入以下内容:

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

这回答了你的主要问题。

您可能希望查看其他几个元素:

  • 在大多数情况下,对于多对多关联,最好使用has_many:through模式
  • 您的订单及其总金额应直接从产品中计算
  • 付款金额可能来自“付款”模式中的记录
  • 为了在语义上正确,产品应描述产品,您现在所称的产品应该是购物卡项目。

无论如何,玩得开心。