I'm trying to replicate the results on checking if a specific record exists. I happen to have a model in a project called Project. I did the following in my console:
irb(main):016> p1 = Project.find(13)
Project Load (0.7ms) SELECT "projects".* FROM "projects" WHERE "projects"."id" = $1 LIMIT $2 [["id", 13], ["LIMIT", 1]]
=>
#<Project:0x000000010a7020a0
...
irb(main):017> p2 = Project.where(id: 13)
Project Load (0.6ms) SELECT "projects".* FROM "projects" WHERE "projects"."id" = $1 /* loading for pp */ LIMIT $2 [["id", 13], ["LIMIT", 11]]
=>
[#<Project:0x000000010a70c820
...
irb(main):018> p1.present?
=> true
irb(main):019> p2.any?
Project Exists? (0.8ms) SELECT 1 AS one FROM "projects" WHERE "projects"."id" = $1 LIMIT $2 [["id", 13], ["LIMIT", 1]]
=> true
It looks to me like using find only executes one query once the object is in memory. Whereas where/any? seems to execute two queries. Did I misunderstand the point of the tip?
will not trigger an additional query. I think that the way Rails is behaving, it's because the query isn't loading in IRB. If you type p2 in the terminal again, I think it will trigger another query.
It looks to me like using find only executes one query once the object is in memory. Whereas where/any? seems to execute two queries. Did I misunderstand the point of the tip?
Then you will find that
will not trigger an additional query. I think that the way Rails is behaving, it's because the query isn't loading in IRB. If you type p2 in the terminal again, I think it will trigger another query.