2016-06-21 77 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