views:

32

answers:

1

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
+2  A: 

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

Tadas Tamosauskas
you could write this in a scope (in the project model): scope :with_tasks, :joins => :tasks, :conditions => 'tasks.project_id = projects.id'then you can use: @projects = Projects.with_tasks
ipsum
you are right, I just haven't noticed title and didn't write this as a scope ;) that happens when you open several tabs and go through all of them. my bad
Tadas Tamosauskas
Join automaticaly adds the condittion given, so there is no need to add :condition like above. The problem with this query is that it returns multiple rows for any given project. Grouping actually solves this, but Postgress wants me to add all 30 fields into group by clause, which is someting I do not really understand. Most important, I messed up the question. What I really need istasks with specific conditions (updated question).
mdrozdziel
You are right - there is no need to add :condition like above. And join by default performs inner join, which means it only selects projects which have tasks. What you have to do is select distinct projects only. I have updated my answer. Hope it helps :)
Tadas Tamosauskas
Ok, this actually solves the question. As for now, I made a instance method for Projects, which returns true if there are open tasks (task.status > 0), and I do simple 'Array.select' on the above query result to get the final result I need. Do you have any idea how to do this just by one SQL query?
mdrozdziel
try adding :conditions => 'tasks.status > 0' to the scope :)
Tadas Tamosauskas
This is working exactly as I need. Thank you very much!
mdrozdziel