ruby-on-rails – 空集合检查返回false而没有条目(Ruby on Rails
发布时间:2020-12-17 01:50:19 所属栏目:百科 来源:网络整理
导读:我有客户模型和设备模型,客户模型has_many:设备和设备模型belongs_to:customer.我试图在客户的主页上显示一个表单,如果customer.devices.empty?如果customer.devices.empty为false,则为true或仅显示客户的设备和附带的详细信息. 我的问题是customer.devic
我有客户模型和设备模型,客户模型has_many:设备和设备模型belongs_to:customer.我试图在客户的主页上显示一个表单,如果customer.devices.empty?如果customer.devices.empty为false,则为true或仅显示客户的设备和附带的详细信息.
我的问题是customer.devices.empty?永远都是假的.通过一些测试,我发现customer.devices.count将始终显示正确数量的设备,但是我只能从customer.devices.empty中获得所需的行为?使用Rails控制台时. 我可以简单地检查customer.devices.count的值,但我真的想用空吗?或任何?检查(我认为)它们是有意的. 问题本身已被描述,但如果你想看代码…… <% 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 解决方法
使用存在?而不是空?:
customer.devices.exists? 存在的区别是什么?通过查询API检查数据库,同时为空?将关联内容检查为标准的Enumerable(可能是脏的/修改的). (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |