Des objets plus en mémoire avec la même id?
-
25-10-2019 - |
Question
Dans mon application rails (v: 3.1) déployée sur Heroku Je suis de plus en objets de même id dans la mémoire. mon journal de la console de Heroku:
>> Project.find_all_by_id(92).size
=> 2
>> ActiveRecord::Base.connection.execute('select * from projects where id=92').to_a.size
=> 1
Comment est-ce possible? Quel pourrait être le problème?
La solution
Solution
There is apparently no duplicate entry in your database according to your SQL query.
Maybe size or length method in your class Project has been overridden. I have tried find_all_by_id and the SQL query seems to be correct.
1.9.2-p180 :006 > Script.find_all_by_id(1).size
Script Load (0.7ms) SELECT "scripts".* FROM "scripts" WHERE "scripts"."id" = 1
=> 1
Hint
If you want to count records you should do it this way
Script.where(id: 1).size
(0.8ms) SELECT COUNT(*) FROM "scripts" WHERE "scripts"."id" = 1
=> 1
Because, as you can see, the count is performed by your database and not by ruby itself. For a dozen of rows you won't see the difference, but if you have thousands or millions...
Autres conseils
irb(main):023:0> ActiveRecord::Base.connection.execute('select count(*) from users where address_id = 22').fetch_hash
=> {"count(*)"=>"4"}
irb(main):024:0> User.find_all_by_address_id(22).size
=> 4
you'd better lookup document about Mysql::Result first