WhereClause.to_h()
Suppose you have two ActiveRecord model classes, Hoge
and Fuga
, and you have a method that fetches a Hoge
record with the appropriate ID of Fuga
.
def super_heavy_method()
subquery = Fuga.first
return Hoge.where(fuga: subquery)
end
At this time, for some reason, you want to extract the ID of Fuga
inside subquery
from the Relation object of Hoge
which is the return value without touching the contents ofsuper_heavy_method ()
.
Once assembled, the ActiveRecord Relation object has several methods that handle the contents of the query. You can get the WhereClause object with the method where_clause ()
, and as the name suggests, you can get the condition of the Where clause as an object. You can retrieve it as a hash with to_h ()
.
query = super_heavy_method()
query.where_clause.to_h() #=> {"fuga_id"=>1}