I am reading the SitePoint book “Rails: Novice to Ninja”. On page 154 we are shown the method .all in relation to an ActiveRecord class/object we created earlier. This method retrieves all records.
On the next few pages, we are shown Story.all.limit and a few others. I have noticed that the limit method works without chaining it from all. I am wondering why we are using the all method here instead of directly calling the methods?
What I thought was happening is we are first getting all the records, and then filtering through those records after. However, after running Story.limit(2) I see the SQL hasn’t changed. Are there any major differences between chaining the method onto all versus not?
I admit I still have a lot more to read, but I thought I’d ask you guys first.
This is a GREAT question. If you are in the development environment your server output will show the actual SQL query that is generated by ActiveRecord. Looking at that you will notice there is some “Rails Magic” taking place; the call to SQL includes a ‘limit 2’ meaning the actual set of records returned from the database is limited. This is more efficient than retrieving ALL and parsing the list down to only [the first] two.
No, that makes sense. It’s built in with the limit method. What about the others, though? I’m just trying to figure out why the author of the book chose to use .all.method instead of just .method.