More objects in memory with the same identifier?

In my rails (v: 3.1) application deployed on heroku, I get more objects of the same identifier in memory. my heroku console log:

>> Project.find_all_by_id(92).size => 2 >> ActiveRecord::Base.connection.execute('select * from projects where id=92').to_a.size => 1 

How is this possible? What could be the problem?

+6
source share
2 answers

Decision

In your database, by your SQL query, there are no duplicate records.

Maybe the size or length method in your class. The project has been redefined. I tried find_all_by_id and the SQL query seems 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 

Tip

If you want to count records, you must do it this way.

 Script.where(id: 1).size (0.8ms) SELECT COUNT(*) FROM "scripts" WHERE "scripts"."id" = 1 => 1 

Since, as you can see, the calculation is performed by your database , and not by ruby ​​itself. For a dozen lines you won't see the difference, but if you have thousands or millions ...

+1
source
 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 better find a Mysql document :: Result First

http://rubydoc.info/gems/mysql/2.8.1/frames

0
source

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


All Articles