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にはメソッド自体に関するドキュメントさえありません)が、ここにかなり詳細な例を示すかなりまともなブログ投稿があります。

また、これがRails3の高度なクエリに関するRailsCastで言及されていることに気づきました。

于 2012-08-09T16:18:01.500 に答える