我在尝试使用另一个模型的值更新一个模型的属性时遇到问题,但这两个模型不相关。
我的模型是:
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”直接属于一个“Order”。
我需要使用“DetailPurchase”产品的属性“quantity”更新“OrderDetail”产品的属性“quantity”。
这个想法是“新” OrderDetail.quantity = “old” OrderDeutil.quantity - DetailPurchase.quantity(显然 product_id 必须相同)
所以,我不知道如何使用“rails 方式”(可能是“Model.find()”、“Model.where()”、“Model.update_attribute()”)“编写”查询或者只是使用一个原始 sql 查询(顺便说一下,我不知道如何编写或执行原始 sql 查询)
你有什么建议吗?谢谢