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.
Assuming we have 2 models with has_many
and belongs_to
relations
respectively:
class User < ActiveRecord::Base
has_many :posts
end
class Post < ActiveRecord::Base
belongs_to :user
end
Now we want to list all posts written by User in a View. Here is what I did at first myself.
Controller:
@user = User.find(params[:id])
# Find all posts by @user
@posts = Post.where("user_id = ?", @user.id)
View:
<% @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.
Controller:
@user = User.find(params[:id])
View:
<% @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 ...in alphabetical order :)
Read more about me in my Résumé