Mirror318
Mirror318

Reputation: 12693

Rails scope for records with children

Is there a simple, easy way to have something like this?

class People < ActiveRecord::Base
  has_many :babies
  scope :with_babies -> { where(babies.count > 0) }
end

There are a bunch of similar questions on SO, but they all resort to complex unique SQL statements. Is there a simple rails way to do it?

Upvotes: 1

Views: 242

Answers (1)

Marcus Ilgner
Marcus Ilgner

Reputation: 7241

You can use a SQL join + distinctness for a simple approach. It might introduce problems in case you want to have non-distinct queries based on this in the future but I don't think this really happens that often so this should get you started. It does indeed provide much better readability than adding custom SQL.

scope :with_babies, -> { joins(:babies).distinct }

Upvotes: 1

Related Questions