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 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).
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With