The following blog post contains material either currently found or soon to be incorporated into my new book, "Easy Active Record for Rails Developers". Among many other topics, you'll learn about model generation, migrations, validations, associations, scopes, joins, includes, forms integration, nested forms, and model testing with RSpec and FactoryGirl. The book is now available, head over to this website's home page to learn more.


This post is short but useful. Most of the Rails applications I work on these days involve a substantial user model complete with Devise integration. These applications maintain a friendly demeanor by referring to the logged-in user by their first or complete (first and last) name, meaning the User model includes attributes such as first_name and last_name. If you are regularly referring to a particular model attribute, you can save a few keystrokes by taking advantage of Ruby’s to_s method. In doing so, you can output the desired object attributes simply by referring to the object rather than bother with expressly identifying the attribute. An example will nicely illustrate the benefit:

class User < ActiveRecord::Base

  def to_s
    "#{first_name} #{last_name}"
  end

end

With the to_s method overridden, I can now retrieve a User object and then output the user’s complete name in the view like so:

class SomeController < ApplicationController

  ...

  def show
    @user = User.find(23)
  end

end

The view might look something like this:

Welcome back, <%= @user %>!

A simple adjustment indeed, but one that can save you some keystrokes over time, not to mention reduce the time spent refactoring should you later decide to just refer to the user by his first name.

Comments