Skip to content

Instantly share code, notes, and snippets.

@tordans
Created November 15, 2011 18:23
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tordans/1367861 to your computer and use it in GitHub Desktop.
Save tordans/1367861 to your computer and use it in GitHub Desktop.
.count vs. .size vs. .lenght
>> p = Project.find_by_id(1114)
# Project Load (1) (0.001019) SELECT * FROM `projects` WHERE (projects.deleted_at IS NULL OR projects.deleted_at > '2011-11-15 18:12:54') ORDER BY projects.id DESC LIMIT 1
=> #<Project id: 1114 …>
>> p.pictures.count
# Always a sql-query
# SQL (1) (0.000572) SELECT count(*) AS count_all FROM `basic_pictures` WHERE (`basic_pictures`.owner_id = 8004 AND `basic_pictures`.owner_type = 'Project') AND ( (`basic_pictures`.`type` = 'ProjectPicture' ) )
=> 60
>> p.pictures.size
# If no ActiveRecord-Object, than .size uses an sql-query
# SQL (1) (0.000949) SELECT count(*) AS count_all FROM `basic_pictures` WHERE (`basic_pictures`.owner_id = 1114 AND `basic_pictures`.owner_type = 'Project') AND ( (`basic_pictures`.`type` = 'ProjectPicture' ) )
=> 60
>> p.pictures.length
# Always an ActiveRecord-Query
# ProjectPicture Load (60) (0.001217) SELECT * FROM `basic_pictures` WHERE (`basic_pictures`.owner_id = 1114 AND `basic_pictures`.owner_type = 'Project') AND ( (`basic_pictures`.`type` = 'ProjectPicture' ) )
=> 60
>> p.pictures.size
# Nothing! Since the ActiveRecord-Object ist already in memory no SQL-Query is needed.
=> 60
>> p.pictures.length
# Nothing. Uses the ActiveRecord-Object out of memory as well.
=> 60
>> p.pictures.count
# Again a new query, even though there is our ActiveRecord-Object in Memory
# SQL (1) (0.001959) SELECT count(*) AS count_all FROM `basic_pictures` WHERE (`basic_pictures`.owner_id = 1114 AND `basic_pictures`.owner_type = 'Project') AND ( (`basic_pictures`.`type` = 'ProjectPicture' ) )
=> 60
>> learn
>> save!
>> exit
>> ;-)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment