2016-09-21 51 views
0

我的模型有如下关系红宝石检查从收集至少一个元素符合条件

class User < ActiveRecord::Base 
    has_many :controllers 
end 

class Controller < ActiveRecord::Base 
    belongs_to :user 
end 

Controller有一个布尔称为is_active

如果属于特定用户对象的所有控制器对象都是is_active false,我想引发异常。

不幸的是我很努力把这句话变成代码。

# 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 

感觉就像有更多的rubisch这样写的。

回答

4

如果is_active是数据库列可能比你想要写:

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

如果需要计算:

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

试轨方式

unless User.find(id).controllers.where(is_active: true).any? 
    #your code 
end 
0
User.joins(:controllers).where(id: id, controller: {is_active: true}).count > 0 
2
user.controllers.any?(&:is_active) 

将是这里最好的选择。