LoginSignup
1
0

More than 3 years have passed since last update.

ActiveRecordで組み立てたRelationオブジェクトからサブクエリを抽出する

Posted at

環境

  • Ruby on Rails 6.1.0

WhereClause.to_h()

HogeFugaというふたつのActiveRecordモデルクラスがあるとして、Fugaの適当なIDでHogeレコードを取ってくるようなメソッドがあるとします。

def super_heavy_method()
  subquery = Fuga.first
  return Hoge.where(fuga: subquery)
end

このとき何らかの理由でsuper_heavy_method()の中身を触らずに、その返り値であるHogeのRelationオブジェクトからsubquery内部にあるFugaのIDを取り出したいとします。

一度組み立てたActiveRecord Relationオブジェクトには、クエリの中身を取り扱うメソッドがいくつか用意されています。where_clause()というメソッドでWhereClauseオブジェクトが取得でき、その名の通りWhere句の条件をオブジェクトとして取得できます。to_h()でハッシュとして取り出すことができます。

query = super_heavy_method()
query.where_clause.to_h() #=> {"fuga_id"=>1}

参考

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0