I have a problem trying to update an attribute of one model using the value from another model, but those two models are not related.
My models are:
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
So, as you can see... a "DetailPurchase" belongs to an "Order", but in an indirect way. And an "OrderDetail" belongs to an "Order" directly.
I need to update the attribute "quantity" of the product of "OrderDetail" using the attribute "quantity" of the product of "DetailPurchase".
The idea is the "new" OrderDetail.quantity = "old" OrderDeatil.quantity - DetailPurchase.quantity (and obviously the product_id has to be the same)
So, i don't know how to "write" the query using the "rails way" (could be "Model.find()", "Model.where()", "Model.update_attribute()") or just use a raw sql query (by the way, I don't know how to write or execute raw sql queries)
What do you recommend? Thanks
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…