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_task
s, 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
精彩评论