mdrozdziel
mdrozdziel

Reputation: 5558

Rails Active Model - scope only objects which have existing members in has_many relation

This seemed trivial at first, but I can't get it right for some time now. The relation is trivial.

class Project < ActiveRecord::Base
  has_many :tasks
end

class Task < ActiveRecord::Base
  belongs_to :project
end

Now I would simply want to get all the Projects which have 1 or more tasks associated. Now to do this without any extended logic (preferably in one query). Backend is on Postgresql.

Edit:

Actually the best would be if I Could get Projects which have tasks with specific conditions. Like:

 task.status > 0

Upvotes: 2

Views: 1524

Answers (1)

Tadas T
Tadas T

Reputation: 2637

scope :having_tasks, :joins => :tasks, :select => 'distinct projects.*', :conditions => 'tasks.status > 0'

Upvotes: 2

Related Questions