Ruby检查集合中的至少一个元素是否满足条件

the*_*ter 2 ruby ruby-on-rails-4

我的模特有以下关系

class User < ActiveRecord::Base
  has_many :controllers
end

class Controller < ActiveRecord::Base
  belongs_to :user
end
Run Code Online (Sandbox Code Playgroud)

Controller的布尔值称为is_active

如果属于特定用户对象的所有控制器对象均为is_activefalse,我想提出一个例外。

不幸的是,我很难将这句话变成代码。

# 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
Run Code Online (Sandbox Code Playgroud)

感觉有更多的rubisch方法可以编写此代码。

spi*_*ann 5

如果is_active是数据库列,则比您可能要写的要多:

Controller.exists?(user_id: id, is_active: true)
Run Code Online (Sandbox Code Playgroud)

如果需要计算:

User.find(id).controllers.any?(&:is_active)
Run Code Online (Sandbox Code Playgroud)