views:

35

answers:

1

Hi,

i have two models:

class Category 
 has many :jobs
end

class Job
 belongs_to :category
end

So for sure i'm able to do

c = Category.first
c.jobs 

My question is: how can i find just categories that has at least one job?

I just forgot to add today i'm executing it like:

Category.find(:all).collect { |x| x if x.jobs.size > 0 }

it works but i'm quite sure that is not optimal.

+1  A: 
Category.find(:all, :joins => :jobs, :group => :id)

Group by is needed to avoid duplications, while the join ensures that only the categories with jobs are selected.

Evgeny Shadchnev