Man*_*ndM 3 ruby collections ruby-on-rails
我有客户模型和设备模型,以及客户模型has_many :devices和设备模型belongs_to :customer.我试图表现出无论是形式,如果添加一个客户的主页上的设备customer.devices.empty?是true如果或者干脆显示客户的设备和相应的细节customer.devices.empty是false.
我的问题是customer.devices.empty?总是返回false.通过一些测试,我已经看到customer.devices.count它将始终显示正确数量的设备,但是我只能customer.devices.empty?在使用Rails控制台时获得所需的行为.
我可以简单地检查的价值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 %>
Run Code Online (Sandbox Code Playgroud)
几乎忘记了我的举止 - 提前感谢任何和所有答案.
-MM
Pin*_*nyM 13
使用exists?而不是empty?:
customer.devices.exists?
Run Code Online (Sandbox Code Playgroud)
不同之处在于exists?通过查询API检查数据库,同时empty?将关联内容检查为标准Enumerable(可能是脏/修改).
| 归档时间: |
|
| 查看次数: |
3550 次 |
| 最近记录: |