Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Empty collection check returning false with no entries (Ruby on Rails)

I have both a Customer model and Device model, and the Customer model has_many :devices and the Device model belongs_to :customer. I'm trying to show either a form to add a device on a customer's home page if customer.devices.empty? is true or simply show customer's device and accompanying details if customer.devices.empty is false.

My problem is that customer.devices.empty? is always returning false. With some tests, I've seen that customer.devices.count will always display the correct number of devices, however I only get the desired behavior out of customer.devices.empty? while using the Rails console.

I can simply check the value of customer.devices.count, but I would really would like to use the empty? or any? checks as (I think) they are intended.

The problem itself has been described but if you'd like to see 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 my manners -- Thanks in advance to any and all answers.

-MM

like image 514
MandM Avatar asked Feb 06 '13 19:02

MandM


2 Answers

Use exists? instead of empty?:

customer.devices.exists?

The difference is that exists? checks the database via the query API, while empty? checks the association contents as a standard Enumerable (which may be dirty/modified).

like image 200
PinnyM Avatar answered Nov 20 '22 12:11

PinnyM


As per your comment exists and count will trigger DB query to check associated devices. When you use build it is not saved in DB so exists returns false and count returns 0. When you use blank it will return false that means it has some devices

customer.devices.blank?
like image 1
Rahul Tapali Avatar answered Nov 20 '22 12:11

Rahul Tapali