Active Record includes and N + 1 Query Problem

Consider the following code books = Book.limit(10) books.each do |book| puts book.author.last_name end In the above code, a query is made each time the lastname of an author of a book is needed in puts book.author.last_name. A single query for each book.…

How to Use Enums in Rails Active Record

Suppose you're making a book tracking app to keep a log of all the books you consume. And you want to log the format. As in, was it an ebook, an audiobook or was it an actual physical paper copy? You would create a column named format on your model.…

Rails Console Commands Cheatsheet

Rails console is useful playground for trying out various view helper commands as well as experimenting with our ActiveRecord data model. Here is a rundown of some things we can do in a Rails console session. Basic commands Reloading the Console We can enter the Rails console by typing rails…

Active Record Association Advanced Topics

What are polymorphic associations? When do we need to create join tables? When do we use single table inheritence? We will cover some more advanced topics with Active Record Associations in this post. Note: This post assumes that you are already familiar with common Active Record associations. You can see…

Rails Active Record Association Basics

In Rails, an association is a connection between two Active Record models. With associations we get convenient utility methods to easily query and do operations on those models. Rails has the following associations belongs_to, has_many, has_one, has_one :through, has_many :through, has_and_belongs_to_many…

Ruby Metaprogramming Part 2

We continue with more reflection methods in Ruby like instance_variables, local_variables, constants for variables and public_methods, private_methods, method_definded? for methods. Note: This is part 2 of metaprogramming in Ruby, in part 1 we covered evaluating strings and blocks with instance_eval and such. Reflection Methods…

Ruby Metaprogramming Part 1

define_method, Kernel.eval, instance_method, instance_eval, class_eval, instance_exec, send, bind. Have you seen Ruby programs with these methods or haven't been sure what each of them do exactly? By the end of this post you will be able to confidently read Ruby code that contains these…

Ruby Method Object, define_method and bind

Ruby methods are executable language constructs. They are not objects. But we can get objects that represents methods with the Object class's method method. Note: This is similar to how blocks are language syntax but not objects in Ruby and we can get object versions of blocks in the forms…