3

In my Rails app, I want to join one table with a named scope of another table. Is there a way to do this without having to rewrite the named scope in pure SQL for my join statement?

Basically, is there a way to do something like this?

class Foo < ActiveRecord::Base
  scope :updated_today, where('updated_at > ?', DateTime.now.prev_day)
end

Bar.joins(Foo.updated_today)

Where Bar.joins generates the following SQL:

SELECT * FROM bars
INNER JOIN
  (SELECT * FROM foos WHERE updated_at > 2012-8-9) AS t0
ON bar_id = bars.id
4

2 回答 2

3

我不相信有任何专门为此设计的方法。但是,您可以使用 的to_sql方法ActiveRecord::Relation将作用域的完整 SQL 查询作为字符串获取,然后您可以将其用作连接语句中的子查询,如下所示:

Bar.joins("INNER JOIN (#{Foo.updated_today.to_sql}) as t0 ON bar_id = bars.id")
于 2012-08-09T17:49:22.550 回答
2

您可以使用该merge方法将范围连接到另一个模型的查询:

Bar.joins(:foos).merge(Foo.updated_today)

我还没有看到关于这方面的大量文档(Rails API 甚至没有关于方法本身的任何文档),但这里有一篇相当不错的博客文章,给出了一个相当详细的示例。

另外,刚刚注意到这在 RailsCast on Advanced Queries in Rails 3中有所提及。

于 2012-08-09T16:18:01.500 回答