Stuck on this one, if you could take a look.. 🙂
What I want is to get all unfinished projects, including all unfinished tasks for a certain user.
This is my setup so far:
User (devise)
has_one :employee
Employee
belongs_to :user
has_and_belongs_to_many :tasks
has_and_belongs_to_many :unfinished_tasks, :conditions => { :tasks => { :completed_at => nil } }, :class_name => "Task"
has_many :unfinished_projects, :through => :unfinished_tasks, :source => :project, :uniq => true ( :include => :unfinished_tasks OR :include => :tasks ? )
Project
has_many :tasks
Task
belongs_to :project
has_and_belongs_to_many :employees
In my view (haml) I’d like to have something like this:
- for project in current_user.employee.unfinished_projects
= project.name
# THESE ARE NOT THE ONLY THE TASKS FOR THE CURRENT_USER
- for task in project.tasks ( OR project.unfinished_tasks ? )
= task.name
This setup works for the projects, there are only projects which have unfinished tasks.
But I’m not sure how to include the unfinished tasks with these projects.
Anyone knows the best way for doing this, I’d like to have a single query for all this if that’s possible.
EDIT:
The tricky part is that the tasks have to be for the current_user.
The projects are loaded perfectly.
But when it loads the tasks:
- for task in project.tasks.unfinished
It does this:
Task Load (1.3ms) SELECT `tasks`.* FROM `tasks` WHERE `tasks`.`project_id` IN (12, 7, 13, 15, 14, 10, 16, 17, 9, 2, 3)
Task Load (0.4ms) SELECT `tasks`.* FROM `tasks` WHERE `tasks`.`project_id` = 12 AND `tasks`.`completed_at` IS NULL
Task Load (0.3ms) SELECT `tasks`.* FROM `tasks` WHERE `tasks`.`project_id` = 7 AND `tasks`.`completed_at` IS NULL
Task Load (0.6ms) SELECT `tasks`.* FROM `tasks` WHERE `tasks`.`project_id` = 13 AND `tasks`.`completed_at` IS NULL
etc.
What it should do is get the tasks of the employee:
Employee
Projects
Tasks
Which should be the tasks that were inner joined in the projects query.
So, after doing this all over again I didn’t really find what my problem was.
There are a few things changed now: I’m using scopes, includes for eager load are in the scope, and no scope on the project.tasks itself.
The project model:
The view:
Gives me this nice MySQL-query:
Works like a charm!
Special thanks to Taryn.. 😉