2016-06-21 78 views
1

我知道有大量的教程解释了如何在模型之间创建'has_many through'关系,但我认为我的问题既是技术性的也是概念性的。三种模型之间的轨道关系令人困惑

  • 的目标是创建一个在线订餐网站
  • 我创建的订单,项目和OrderItem的车型。

关系:

class OrderItem < ActiveRecord::Base 
    belongs_to :item, conditions: "active = true" 
    belongs_to :order 
end 

class Order < ActiveRecord::Base  
    belongs_to :user 
    has_many :order_items 
    has_many :items, through: :order_items 

    validates :status, inclusion: { in: %w(ordered completed cancelled) }  
end 

class Item < ActiveRecord::Base  
    has_and_belongs_to_many :categories, join_table: :items_categories 

    has_many :order_items 
    has_many :orders, through: :order_items 

    validates_presence_of :title, :description 
    validates :price, numericality: { :greater_than=>0 }  
end 

难道我做错了什么?每个订单应该能够包含许多物品和数量。 我不是很积极我正在为这些模型做正确的架构,因为我不能通过< <操作员分配数量,只分配项目。

谢谢你的时间。

+0

¿?你在控制台中的命令是什么?我在OrderItem模型 – DennisCastro

+0

Dennis中看不到数量属性,数量是在迁移中设置的,在order_items表中有一个具有此名称的列。我应该如何设置订单项目?我对此事有怀疑.. –

回答

2

这样

order = Order.new(user: @user) 
order.order_items << OrderItem.new(quantity: 100, item: Item.first) 
+0

太棒了!谢谢你:)欢迎光临 –

+0

。直到下一次 – DennisCastro