【问题标题】:How to specify join conditions in Rails for belongs_to assocation?如何在 Rails 表单belongs_to 关联中指定连接条件?
【发布时间】:2010-11-14 02:46:48
【问题描述】:

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

例如,我想将产品加入定价点。产品具有价格,定价点具有最小和最大数量以及名称。例如。最小值 = 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

提前感谢您的帮助,

大写

【问题讨论】:

    标签: ruby-on-rails activerecord join associations


    【解决方案1】:

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

    您需要执行以下操作:

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

    为方便起见,您可以将其移至 Products 类中的方法。

    另一种选择是为此使用原始 SQL。

    【讨论】:

    • 是的,我认为可能是这样。我想映射关联,因为我正在使用 Thinking Sphinx,并且我想在我的搜索索引中使用该关联。不过感谢您的帮助。
    猜你喜欢
    • 2013-04-22
    • 1970-01-01
    • 2015-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多