alejorivera
alejorivera

Reputation: 945

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.

What I'm looking to implement is:

if @card.submissions.any?
  render @card.submissions
end

Upvotes: 11

Views: 2625

Answers (2)

mk7
mk7

Reputation: 215

An old question, but I would like to chip in nonetheless. I came across a similar issue, and found:

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

even though there were no records in my database, but I had initialised an empty @card.submission object which was in the @card.submissions array.

To mitigate this problem, I tried

@card.submissions.all.any?

which reloaded the array from the database, and returned false.

Upvotes: 0

Philip Hallstrom
Philip Hallstrom

Reputation: 19879

Looks like Submission is a new record (since id is nil). If it's new, it hasn't made it to the database yet. count makes a SQL call to the database to determine the number of rows so is rightly returning zero. any? is returning true since there is an object in the collection.

What happens if you try @card.submissions.to_a.size (to ensure you load them from the database then check the size of the array).

Upvotes: 14

Related Questions