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

+3


source to share


2 answers


Use exists?

instead empty?

:

customer.devices.exists?

      



The difference is that it exists?

validates the database using the Query API, but empty?

validates the content of the association as a standard Enumerated (which can be dirty / modified).

+10


source


As per your comment exists

and count

runs a query DB

to check related devices. When you use an assembly, it is not stored in DB

, so it exists

returns false

and count

returns 0

. When you use blank

it will return false

, which means it hasdevices



customer.devices.blank?

      

+1


source







All Articles