I have a simple time-tracking app, that has projects, tasks, and entries.
The setup is straight-forward:
class Project < ActiveRecord::base
has_many :tasks
has_many :entries, :through => :tasks
end
class Task < ActiveRecord::base
belongs_to :project
has_many :entries
default_scope order("name asc") # this causes problems
end
(Entry is entirely straight-forward, so I’ve left it out)
However, I’m running into trouble when trying to do custom ordering of entries selected from a project. Specifically, I’m trying to select the latest entry like so:
latest_entry = project.entries.order("created_at desc").first
But due to the :through => :tasks and the default_scope that Task has, the actual query that Rails executes becomes:
SELECT `entries`.* FROM `entries`
INNER JOIN `tasks` ON `entries`.`task_id` = `tasks`.`id`
WHERE `tasks`.`project_id` = 23
ORDER BY name asc, entries.date desc LIMIT 1 -- wrong order!
Note the ORDER BY clause – it includes the default_scope from Task, and only after that does it include the order I specified.
So basically, I don’t get the latest entry of all entries in the project, but only the latest in the first task.
Is there any way around that? Seems like there should be a way to ignore/negate default_scope on a through-model (without completely dropping the default_scope)
How about reorder: