0

我在尝试使用另一个模型的值更新一个模型的属性时遇到问题,但这两个模型不相关。

我的模型是:

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 查询)

你有什么建议吗?谢谢

4

1 回答 1

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

话虽如此,您可能需要更改一些内容:

首先,您几乎肯定不应该有一个名为 'order' 的模型—— order 也是一个 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;有关详细信息,请参阅API

于 2011-08-12T20:12:26.620 回答