Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 912
alejorivera Avatar asked Jul 02 '15 19:07

alejorivera


1 Answers

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).

like image 183
Philip Hallstrom Avatar answered Oct 28 '22 07:10

Philip Hallstrom