Ruby on Rails magic: models relation

5 months ago I demonstrated a convention of RoR that makes it possible to render Model objects in their corresponding partials in just one line with expressive syntax:

<%= render @users %>

Today I want to show another tip I learned about ActiveRecord from this tutsplus course recorded by José Mota.

#Accessing a model via it's parent

Assuming we have 2 models with has_many and belongs_to relations respectively:

class User < ActiveRecord::Base
  has_many :posts
class Post < ActiveRecord::Base
  belongs_to :user

Now we want to list all posts written by User in a View. Here is what I did at first myself.


@user   = User.find(params[:id])
# Find all posts by @user
@posts  = Post.where("user_id = ?",


<% @posts.each do |post| %>
  <p><%= post.title %></p>
<% end %>

Did you already notice where I wrote too much? Well, of course in Controller. Assigning User to @user was more than enough as our User model has has_many relation with Post model and so posts can be accessed via @user.posts due to magic provided by ActiveRecord.

Let's take a look at a more expressive code that accomplishes exactly the same result.


@user = User.find(params[:id])


<% @user.posts.each do |post| %>
  <p><%= post.title %></p>
<% end %>


This is a clear example where most generic complexity can be be hidden behind the scenes and only self-explanatory command executions operate the main program logic. The importance of this aspect increases with codebase growth.

The more self-explanatory code we write, the less human-readable comments we have to add.

Hi, I'm Sergey, 30yo, father of 2, currently based in Tel Aviv, Israel.

I'm mostly passionate about #music, #programming, #sport, #ui, #ux alphabetical order :)

Read more about me in my Résumé