Ruby on Rails: #any? returns an invalid value

In my models I have users ( User ) and stories ( Story ), with the relation: user has_many stories .

I noticed something strange in my shell:

 (dev) user.stories.any? => true (dev) user.stories Story Load (1.6ms) SELECT "stories".* FROM "stories" WHERE "stories"."user_id" = 703 ORDER BY created_at ASC [["user_id", 703]] => [] (dev) user.stories.any? => false 

How it works? Is this related to my code, or is it some kind of bug in Rails and a way to query the database?

+5
source share
1 answer

The workaround I found (thanks to @ house9) is to use:

 user.stories.to_a.any? user.stories.to_a.empty? # also works with empty? 

Therefore, Rails is forced to make a request. And the overhead is pretty low, since to_a.any? executes the request only once a few times.

Or better , as @Jordan suggested, use:

 user.stories.exists? 
0
source

Source: https://habr.com/ru/post/1239358/


All Articles