Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between these two statements, and why would you choose them?

I'm a beginner at rails. And I've come to understand two different ways to return the same result.

What is the difference between these two? And what situation would require you to choose one from the other?

Example 1:

Object.find(:all).select {|c| c.name == "Foobar" }.size

Example 2:

Object.count(:conditions => ['name = ?', 'Foobar'])

FURTHER NOTE:

I seriously wish I could vote everyone correct answers for this one. Thank you so much. I just had a serious rails affirmation.

like image 467
Trip Avatar asked Dec 17 '22 22:12

Trip


1 Answers

Object.count always hits the DB, and the find()....size() call can optimize. Good discussion here

http://rhnh.net/2007/09/26/counting-activerecord-associations-count-size-or-length

like image 110
Lou Franco Avatar answered Feb 22 '23 23:02

Lou Franco