3

我正在尝试使用连接条件而不是外键在两个模型之间创建关联。有谁知道这是否可能?

例如,我想将产品加入定价点。产品具有价格,定价点具有最小和最大数量以及名称。例如。最小值 = 0,最大值 = 20,名称 = 不到 20 美元。产品之间的关联在于价格以及最小值和最大值。

SELECT *
FROM products
INNER JOIN pricing_points
ON pricing_points.minimum < products.price AND pricing_points.maximum >= products.price

这有意义吗?所以我想要在我的模型中这样的东西:

class Product < ActiveRecord::Base

  belongs_to :pricing_point, :join => "INNER JOIN pricing_points ON pricing_points.minimum < products.price AND pricing_points.maximum >= products.price"

  ...

end

在此先感谢您的帮助,

帽子

4

1 回答 1

1

您无法使用 ActiveRecord 真正定义这种类型的关系。AR 提供 :conditions 选项,但它仅适用于查询的 WHERE 部分,它仍会尝试加入pricing_point_id =pricing_point.id。

您需要执行以下操作:

Products.find :all, :joins => "INNER JOIN pricing_points \
    ON pricing_points.minimum < products.price \
    AND pricing_points.maximum >= products.price"

You can move this to a method in your Products class for convenience.

Another option is to use raw SQL for this.

于 2009-07-26T08:40:31.867 回答