2011-08-11 17 views
0

我嘗試使用另一個模型的值更新一個模型的屬性時出現問題,但這兩個模型都是不相關的。Ruby on rails 3 - 加入許多模型,使用來自另一個模型的屬性更新一個模型的字段,不直接相關

我的車型有:

class Order < ActiveRecord::Base 
    has_many :order_details 
    has_many :waybills 
end 

class OrderDetail < ActiveRecord::Base 
    belongs_to :order, :foreign_key => "order_id" 
    belongs_to :product, :foreign_key => "product_id" 
end 

class Waybill < ActiveRecord::Base 
    has_many :purchases 
    belongs_to :order, :foreign_key => 'order_id' 
end 

class Purchase < ActiveRecord::Base 
    belongs_to :waybill, :foreign_key => 'waybill_id' 
    has_many :detail_purchases 
end 

class DetailPurchase < ActiveRecord::Base 
    belongs_to :purchase, :foreign_key => 'purchase_id' 
    belongs_to :product, :foreign_key => 'product_id' 
end 

所以,你可以看到... ...一個「DetailPurchase」屬於一種「訂單」,但以間接的方式。而「OrderDetail」直接屬於「訂單」。

我需要使用「DetailPurchase」產品的屬性「數量」更新「OrderDetail」產品的屬性「數量」。

的想法是「新」 OrderDetail.quantity =「老」 OrderDeatil.quantity - DetailPurchase.quantity(明明的product_id必須是相同的)

所以,我不知道如何「 (「可能是」Model.find()「,」Model.where()「,」Model.update_attribute()「)或者只是使用一個原始的sql查詢(順便說一下,我寫」不知道如何編寫或執行原始的sql查詢)

你有什麼建議?謝謝

回答

0

如果我理解你的問題,你試圖找到給定DetailPurchase的(鬆散)相關聯的OrderDetail。要做到這一點,你可以這樣做:

class DetailPurchase < ActiveRecord::Base 
    belongs_to :purchase, :foreign_key => 'purchase_id' 
    belongs_to :product, :foreign_key => 'product_id' 

    # Goes up the associations to find the Order at the top of the belongs_to associations 
    def parent_order 
    purchase.waybill.order 
    end 

    # Given the parent_order, find the first order_detail that matches our product_id 
    def order_detail 
    parent_order.order_details.first.where(["product_id = ?", product_id]) 
    end 
end 

話雖這麼說,有一個你可能想改變一些東西:

首先,你幾乎肯定不應該有一個名爲模式「訂單' - 命令也是一個ActiveRecord實例方法(如在ClassName.all.order("name ASC")),所以你打開自己的世界受到傷害。

當您的某個模型更改其他模型中的某個聚合值時,它似乎也有點問題;你將有所有棘手的邏輯來處理編輯或刪除OrderDetails時。對OrderDetail.quantity使用集合函數可能更有意義 - 換句話說,在創建時設置OrderDetail.original_quantity,然後將OrderDetail.quantity計算爲OrderDetail.original_quantity minus the sum of the relevant purchase detail quantities。如果你想走這條路線,我會忽略上面的代碼,並將purchase_details作爲範圍方法添加到OrderDetail;詳情請參閱the API

+0

你是對的我的模型不叫「訂單」這是一個更長的名字,但我張貼「訂單」縮短。我知道當他們沒有關係時,試圖從另一個模型的「更新」一個模型的值有點奇怪,但在這種情況下,我真的需要這樣做。我會檢查API,我會盡力解決我的問題。謝謝你的幫助 – Angelo

相關問題