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.
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)
user.controllers.any?(&:is_active)
would be the best option here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With