Check if at least one record have a given attribute set to true
Asked Answered
L

1

9

Two models:

class Task < ActiveRecord::Base
  has_many :subtasks

end

class Subtask < ActiveRecord::Base
  belongs_to :task

end

Subtask have boolean attribute that set to true if subtask is complete.

How can i check if a task has at least one completed subtask?

Lalalalage answered 28/3, 2012 at 18:22 Comment(0)
L
22

The simplest possible thing would be

task.subtasks.where(:completed => true).exists?

If you define a completed scope on subtasks this could be shortened to

task.subtasks.completed.exists?

Both of these will fire a database query, so if you already have the subtasks loaded (task.association(:subtasks).loaded?) it will probably be quicker to manipulate the ruby objects via somethig like

task.subtasks.any? {|subtask| subtask.completed?}
Larousse answered 28/3, 2012 at 18:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.