I have a time tracking application that has projects, tasks and records.
The configuration is straightforward:
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 completely straight forward, so I left it)
However, I encountered difficulties when trying to individually order records selected from the project. In particular, I am trying to select the last entry, for example:
latest_entry = project.entries.order("created_at desc").first
But because of :through => :tasks and default_scope that Task has, the actual request made by Rails 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
Pay attention to ORDER BY clause - it includes default_scope from Task , and only after that it includes the order I specified.
So basically, I am not getting the last record of all the records in the project, but only the last in the first task.
Is there any way? There seems to be a way to ignore / negate default_scope on through models (without completely resetting default_scope )
source share