Useful ActiveRecord methods

Page 1

Useful ActiveRecord methods

After we mentioned some of the best tips and methods for writing a better Ruby code, we also encouraged you to learn more about methods in Ruby. And today we will help you with this task by providing some entry but necessary information on useful ActiveRecord methods. These methods will help you to solve N+1 queries problem and to achieve the results faster! Particularly we will talk about the next ActiveRecord methods: 1. #preload method 2. #eager_load that creates SQL query using LEFT OUTER JOIN 3. #includes method They are recommended as a solution for solving N+1 queries problem. These 3 methods dramatically reduce the time for preload related data. But if you have no need in this you may also use #lazy-loading Another stack of methods to achieve results faster, especially if we talk about making a database available for performing other operations, are here: 1. #pluck method if we want to retrieve a list of IDs (primary keys) from a database (but it can’t be used to map records) 2. #sum method 3. #update_all for updating all the records in a single query Ruby will take longer to process the same query, but at the same time, the database will available for performing other operations. Thanks to Marcin Jakubowski for this scope! p.s. These are the 5 Ruby methods you should know too!


Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.