Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 594
theDrifter Avatar asked Nov 27 '25 01:11

theDrifter


2 Answers

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)
like image 165
spickermann Avatar answered Nov 29 '25 16:11

spickermann


user.controllers.any?(&:is_active)

would be the best option here.

like image 23
Pandya M. Nandan Avatar answered Nov 29 '25 17:11

Pandya M. Nandan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!