ruby-on-rails

4 minor Rails features you should remember

Follow me
Follow me

Latest posts by Tomasz Antas (see all)

Jun 28, 2015

4 minor Rails features which you could forget or even haven’t noticed.

 

 

Iterate over a large set of records (find_each and find_in_batches)

(From guides.rubyonrails.org)

Let’s assume that we want send a newsletter to a large set of users:

In inefficient way (1), Active Record will build a model object for each row and keep entire array in memory. If we have a large number of records, the entire collection may exceed the amount of available memory. find_each method retrieves a batch of records (1000 records by default) and then yields each record to the block individually as a model. This process is repeated until all of the records have benn processed.

find_in_batches is a method similar to find_each. The difference is that find_in_batches yields batches to the block as an array of models.

 

Eager Loading Associations

(From guides.rubyonrails.org)

It’s the mechanism for loading the associated records of the objects returned by Model.find using as few queries as possible.

With includes, Active Record ensures that all of the specified associations are loaded using minimum possible number of queries.

 

Find or Build a New Object

(From guides.rubyonrails.org)

find_or_create_by method allows to add new record, if searched object doesn’t exists.

find_or_create_by method checks whether an User with name Andy exists. If it doesn’t, then create method is called.

 

Using content_for method in views

(From guides.rubyonrails.org)

The content_for method in specific view allows to overwrite a named yield element in layout. For example, the layout is:

The specific view is:

The result of rendering would be:

 

 

 

 

 

 

 

 

Tomasz Antas4 minor Rails features you should remember