Rails model methods

September 10, 2018

When I was first starting with Rails, I was excited to learn a skill to keep my views clean: you can define methods inside your models and call them with ordinary dot notation. This is a great approach if you find yourself adding repetitive formatting logic to your views.

To keep this example simple and easy to understand, I’ll create a “fake” username by pulling the user’s email, taking everything before the @, and capitalizing the first letter. So mark@example.com would return Mark. I’d do this inside user.rb:

user.rb
class User < ApplicationRecord
  def username
    self.email.split('@')[0].capitalize
  end
end

Then, inside a view, you could just pull the username off of user:

show.html.erb
<p>
  This post was written by <%= @post.user.username %>.
</p>

Calling user.username will look for the username method on the User model. This helps you avoid code duplication and is also much easier to read than the alternative:

show.html.erb
<!-- Not Good -->
<p>
  This post was written by <%= @post.user.email.split('@')[0].capitalize %>.
</p>