followfung
followfung

Reputation: 53

Get all parent records where their first child has a specific property

I'm trying to create an ActiveRecord query to retrieve all parent records where their first child has a specific property.

Parent has_many children
Child has_one parent

Essentially I'm trying to do:

Parent.includes(:children).where('child.first.property = ?', 'something')

How can I achieve something like this?

Upvotes: 1

Views: 617

Answers (1)

T J
T J

Reputation: 1342

It might be easier to perform those checks in your code and worry about optimization later.

Parent.select { |p| p.children.order("created_at asc").first.property == "something" }

That will end up loading up the first child for each parent though. Another option would be to first join with children that have that attribute to narrow down the parents and then to perform the same check above.

Parent.joins(:children).where(:property => "something").group("parents.id").select { |p| p.children.order("created_at asc").first.property == "something" } 

Upvotes: 1

Related Questions