2

I want to find things that have some children. So given:

class Foo < ActiveRecord::Base
   has_many :bars
   has_many :bazes

   scope :is_a_parent ...what goes here?...

I want to get Foos that have any bars or any bazes. Certainly all things are possible with raw SQL, exists (select 1 from bars ...) or exists (select 1 from bazes ...), but yuk.

Surely there's some way to use any? in conjunction with arel or method? Some other way to do it without resorting to SQL?

Tim Scott
  • 15,106
  • 9
  • 65
  • 79

2 Answers2

0

Does this help you? That prior answer is looking for the inverse of yours (Foos that have no bars nor bazes) but you should be able to invert the logic.

Community
  • 1
  • 1
GoZoner
  • 67,920
  • 20
  • 95
  • 145
  • This won't work. It wouldn't work even for one collection because it would return multiple rows for each Foo. Maybe AR would sort that out, but it's risky and hackish to count on that. Anyway, I'm pretty sure it falls flat for my scenario of two child collections. – Tim Scott Jun 09 '12 at 00:54
0
class Foo < ActiveRecord::Base
  has_many :bars
  has_many :bazes    

  scope :is_a_parent, (joins(:bars) or joins(:bazes)).uniq

would give you all foos having a bar or a baze

Btw, usually functions starting with "is_", should end with "?", and should return only true/false.

Amol Pujari
  • 2,280
  • 20
  • 42