空集合检查返回false没有条目(Ruby on Rails)

问题描述:

我有一个客户模型和设备模型,客户模型has_many :devices和设备模型belongs_to :customer。如果customer.devices.empty?true或者只是显示客户的设备和相关详细信息(如果customer.devices.emptyfalse),我试图显示一个表单以在客户的主页上添加设备。空集合检查返回false没有条目(Ruby on Rails)

我的问题是customer.devices.empty?总是返回false。通过一些测试,我已经看到customer.devices.count将始终显示正确数量的设备,但是在使用Rails控制台时,我只能得到customer.devices.empty?以外的所需行为。

我可以简单地检查customer.devices.count的值,但我真的想用empty?any?检查(我认为)它们是有意的。

问题本身已经说明,但如果你想看到的代码...

<% if customer.devices.count == 0 %> 
    Count is 0 <!-- This is displayed on the page --> 
    <% end %> 
    <% if customer.devices.empty? %> 
    Customer has no devices! <!-- This is NOT displayed on the page --> 
    <% end %> 
    <% if customer.devices.any? %> 
    Customer has <%= pluralize(customer.devices.count, "device") %>. 
    <!-- The line above prints "Customer has 0 devices." --> 
    <% end %> 

差点忘了我的方式 - 在此先感谢任何和所有答案。

-MM

+0

你有没有加载(但不保存)在该客户的所有设备? '.count'方法总是会触发一个数据库查询,而'empty?'如果关联已经被加载则不会。请发布相关的控制器代码... – PinnyM

+0

因此,基本上,我是否已将某个设备与某个客户关联起来(例如,在某处执行'@device = customer.devices.build(params [:device]'),而没有实际执行'@device .save'?我创建了一个全新的用户,默认情况下,它没有关联的设备,我意识到一些奇怪的东西。我使用了一组帮助函数,让我跟踪不同页面上的客户(使用cookie) ,以及引用辅助功能的站点“home”页面显示错误的结果,而如果我转到customers/3,它可以直接访问'@ customer'变量,并显示正确的一切。 – MandM

+0

是的,这种行为如果你想查看未被执行的数据,使用Enumerable方法('any?','empty?'),否则使用查询API – PinnyM

使用exists?代替empty?

customer.devices.exists? 

的区别在于exists?检查经由查询API数据库中,而empty?检查关联内容作为标准可枚举(其可以是脏/修改)。

+0

这可行,但如果你看看我对上述评论的回应,会在客户的页面上“清空”工作(即, 。在访问customer/3并直接访问@customer变量之后),而不是当我使用一个帮助函数,通过@customer || = Customer.find_by_remember_token(cookies [:remember_token])来获得@customer变量时? – MandM

+0

@MandM:如果你还没有操作'@ customer.devices'集合,'empty?'将别无选择,只能检查数据库。如果集合已经实例化(通过单独的数据库调用,或通过手动操作),它将简单地检查集合的当前状态。 – PinnyM

根据您的意见existscount将触发DB查询来检查关联的设备。当您使用生成它不保存在DB所以exists返回falsecount返回0。当您使用blank它将返回false,这意味着它有一些devices

customer.devices.blank? 
+0

想接受这两个答案,但Pinny在几分钟之前就滑了下来。谢谢! – MandM

+0

'exists?'稍微更有效一些,因为数据库可以使用更高性能的EXISTS(如果可用),而'blank?'将调用COUNT。但是,两者都会返回相同的结果。 – PinnyM