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
Use
exists?instead ofempty?:The difference is that
exists?checks the database via the query API, whileempty?checks the association contents as a standard Enumerable (which may be dirty/modified).