Object.count returns 0. But object.any? returns true. What's happening?

@card.submissions returns this:

 <ActiveRecord::Associations::CollectionProxy [#<Submission id: nil, user_id: nil, card_id: 7, created_at: nil, updated_at: nil, text: "">]> 

@card.submissions.any? returns true .

@card.submissions.count returns 0 .

I want to implement:

 if @card.submissions.any? render @card.submissions end 
+7
ruby ruby-on-rails activerecord
source share
2 answers

It looks like the View is a new entry (since id is zero). If it is new, it has not yet entered the database. count makes an SQL call to the database to determine the number of rows, so it returns zero correctly. any? returns true since there is an object in the collection.

What happens if you try @card.submissions.to_a.size (to make sure you download them from the database, then check the size of the array).

+9
source share

An old question, but nonetheless I would like to talk. I ran into a similar problem and found:

 @card.submissions.any? = true @card.submissions.count = 0 

although there were no entries in my database, but I initialized the empty @card.submission object, which was in the @card.submissions .

To mitigate this problem, I tried

 @card.submissions.all.any? 

which reloaded the array from the database and returned false .

0
source share

All Articles