theDrifter theDrifter - 2 months ago 7
Ruby Question

Ruby Check if at least one element from collection meets condition

My models have the following relation

class User < ActiveRecord::Base
has_many :controllers
end

class Controller < ActiveRecord::Base
belongs_to :user
end


Controller
has a boolean called
is_active
.

I would like to raise an exception if all controller objects which belong to a specific user object are
is_active
false.

Unfortunately i struggle putting this sentence into code.

# if for all controllers is_active false is met, raise exception
# ~> need to find one controller which is active
array = []
User.find(id).controllers.each do |c|
array << c.is_active
end
unless array.include?('true')
raise ...
end


It feels like there is a more
rubisch
way to write this.

Answer

If is_active is a database column than you might want to write:

Controller.exists?(user_id: id, is_active: true)

If is needs to be calculated:

User.find(id).controllers.any?(&:is_active)