我嘗試使用另一個模型的值更新一個模型的屬性時出現問題,但這兩個模型都是不相關的。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查詢)
你有什麼建議?謝謝
你是對的我的模型不叫「訂單」這是一個更長的名字,但我張貼「訂單」縮短。我知道當他們沒有關係時,試圖從另一個模型的「更新」一個模型的值有點奇怪,但在這種情況下,我真的需要這樣做。我會檢查API,我會盡力解決我的問題。謝謝你的幫助 – Angelo