Rails associations: where clause with hash parameters
mouse 413 · person cloud · link
Last update
2017-07-29
2017
07-29
«Rails AREL "where" magic! Stop using hardcoded SQL!»

Given this sample class with two relations on the same table:

1
2
3
4
def Edge < ActiveRecord::Base
    belongs_to :first , class_name: 'Node'
    belongs_to :second, class_name: 'Node'
end

If you want to query edges by the first node, you could do this:

1
Edge.joins(:first).where(nodes: {value: 1})
1
2
3
SELECT "edges".*
FROM "edges" INNER JOIN "nodes" ON "nodes"."id" = "edges"."first_id"
WHERE "nodes"."value" = 1

But if you have to query using both nodes, you can still use joins like this:

1
Edge.joins(:first, :second).where(nodes: {value: 1}, seconds_edges: {value: 2})
1
2
3
4
5
6
SELECT "edges".*
FROM "edges"
  INNER JOIN "nodes" ON "nodes"."id" = "edges"."first_id"
  INNER JOIN "nodes" "seconds_edges" ON "seconds_edges"."id" = "edges"."second_id"
WHERE "nodes"."value" = 1
  AND "seconds_edges"."value" = 2

Source: Stackoverflow