开发者

Ruby on Rails: Finding all "incomplete tasks" through named_scope

开发者 https://www.devze.com 2022-12-11 12:22 出处:网络
I have two models: (1) Task, and (2) CompletedTask. I\'m looking to do a named_scope for :incomplete_tasks (tasks that don\'t 开发者_如何学Pythonhave any entries in the completed_tasks table)

I have two models: (1) Task, and (2) CompletedTask.

I'm looking to do a named_scope for :incomplete_tasks (tasks that don't 开发者_如何学Pythonhave any entries in the completed_tasks table)

I'm thinking it would be something like this in my Task model:

named_scope :incomplete_tasks, :conditions => **completed_tasks.empty?**

Do you know how I find all incomplete tasks correctly?


Assuming that a Task has_one :completed_task and CompletedTask belongs_to :task:

named_scope :incomplete_tasks, :conditions => 'not exists (select 1 from completed_tasks where tasks.id = completed_tasks.task_id')

Another option is to use a left outer join and checking for null completed_tasks, but you need to specify a :select in that case:

named_scope :incomplete_tasks, :select     => 'tasks.*',
                               :joins      => 'left outer join completed_tasks on tasks.id = completed_tasks.task_id'
                               :conditions => 'completed_tasks.id is null'

The first is definitely more readable, but subselects are less performant on some databases, so give them a shot decide

0

精彩评论

暂无评论...
验证码 换一张
取 消