Empty collection check returns false with no records (Ruby on Rails)
I have a customer model and a device model, and a Customer has_many :devices
model and a device model belongs_to :customer
. I am trying to show a form to add a device to the client home page if customer.devices.empty?
is true
or just show the client device and accompanying data if customer.devices.empty
- false
.
My problem is that it customer.devices.empty?
always returns false. In some tests I have seen that it customer.devices.count
always displays the correct number of devices, however I am getting the desired behavior from customer.devices.empty?
when using the Rails console.
I can just check the value customer.devices.count
, but I would really like to use tags empty?
or any?
how (I think) they are intended.
The problem itself is described, but if you want to see the code ...
<% 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 %>
Almost forgot about my manners - Thanks in advance for any answers.
-MM
source to share