2015-06-08 207 views
0

我有一個在線訂購應用程序。這裏是我有的結構:Rails模型最佳實踐

訂單有很多items_variations,item_variations屬於項目。訂單屬於客戶。項目有一個價格(列)。

現在的訂單模型我有一個查詢查找訂單金額,以及單項金額像這樣

def self.order_amount 
    Order.joins(:items).where(customer_id: customer_id).sum('items.price') 
end 

def amount_item 
    ItemVariation.joins(:items).where(order_id: self.id).sum('items.price') 
end 

這是爲了使這種模式的正確方法是什麼? AFAIK,我不應該在order.rb中使用ItemVariation,但我想不出更好的方法。

+0

是否'ItemVariation'也belong_to'Order'? – thebenedict

+0

@thebenedict是的。 – Amit

回答

0

您可以使用has_many: through

在Order.rb:

has_many :items, through: :item_variations 

def amount_item 
    items.sum(:price) 
end 
+0

有沒有一種方法可以改善order_amount – Amit

+0

也許,但很難說沒有看到你的模型。 'order_amount'和'amount_item'有什麼區別?理想情況下,一個訂單屬於一個客戶,所以'order_amount'應該是'items.sum(:price)' – thebenedict

+0

實際上,在這種情況下,我們有兩個(更多在未來)用戶組合他們的訂單的選項,因此每個訂單有2個客戶(現在)。 – Amit