【问题标题】:Search for a Dataset where a associated Dataset has a specific value using Active-Record?使用 Active-Record 搜索关联数据集具有特定值的数据集?
【发布时间】:2014-07-17 13:03:42
【问题描述】:

我目前正在尝试在我的数据集中进行“复杂”搜索。 我想找到与特定工具关联的每个数据集。 我试过这样的事情:

Dataset.find_by_sql("SELECT * FROM datasets, tools, sectors, products  WHERE datasets.id = sectors.dataset_id AND sectors.product_id = products.id AND products.tool_id = tools.id AND tools.name = '#{toolname}'")

这很好用。但是我们想为查询定义范围,以便以后能够组合其中的一些,例如:Dataset.find_by_toolname("foo").find_by_sector_name("foo2")。所以我为此定义了一个范围:

scope :with_tool_name, ->(toolname) {find_by_sql("SELECT * FROM datasets, tools, sectors, products  WHERE datasets.id = sectors.dataset_id AND sectors.product_id = products.id AND products.tool_id = tools.id AND tools.name = '#{toolname}'")}

这里的问题是这个查询将返回一个数组而不是一个 ActiveRecord-Relation,因此我无法对第一个结果执行另一个范围请求。

那么我如何获取某个关联模型的属性具有特定值的数据......然后在此应用另一个范围?

数据模型如下所示:

【问题讨论】:

    标签: sql ruby-on-rails database activerecord


    【解决方案1】:

    您可以使用 activerecord 方法 joins()。并且每个连接的结果都可以与方法 merge() 混合在一起。这里有一个小例子来获取一个 tool_id 的所有数据集。

    Dataset.joins(:sectors).merge(Sector.joins(:product)).merge(Product.joins(:tool).where(:tool_id => 1))

    【讨论】:

    • 谢谢,真的很有帮助。
    猜你喜欢
    • 2013-04-28
    • 2013-05-13
    • 1970-01-01
    • 2020-02-02
    • 2019-12-04
    • 1970-01-01
    • 2017-10-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多