Nicer printing of Rails models

I like my models to be printed nicely, to make the class of the model as well as the id and other data available, so, when they end up in a log or console, I can now exactly what it is. I’ve been doing this since before Rails 3 and since Rails projects now have an ApplicationRecord class, it’s even easier.

On my global parent for all model classes, ApplicationRecord I add this:

def to_s(extra = nil)
  if extra
    extra = ":#{extra}"
  end
  "#<#{self.class.name}:#{id}#{extra}>"
end

That makes all records automatically print as:

<ModelName:id>

For example:

<User:123>

which makes the record findable.

But also, allows the sub-classes to add a bit of extra information without having to re-specify the whole format. For example, for the User class, it might be:

  def to_s
    super(email)
  end

so that when the user gets printed, it ends up being:

<User:123:sam@example.com>

which I found helps a lot with quickly debugging issues, in production as well as development environments.

You may also like:


2 responses to “Nicer printing of Rails models”

  1. Dmitry Non Avatar

    Hey!
    Neat trick, I’ve done something similar but never in AR models.
    I would suggest using `#inspect` though. `#to_s` may unintentionally end up somewhere in production frontend (through interpolation) and expose something we don’t want to (like a personal email). `#inspect` I *think* should be picked up by repls (irb, pry) automatically and can be used for logging through `puts user.inspect`

  2. Nondv Avatar

    Hey!
    Neat trick, I’ve done something similar but never in AR models.
    I would suggest using `#inspect` though. `#to_s` may unintentionally end up somewhere in production frontend (through interpolation) and expose something we don’t want to (like a personal email). `#inspect` I *think* should be picked up by repls (irb, pry) automatically and can be used for logging through `puts user.inspect`

Leave a Reply

Hi, I'm Pablo, this is my web site. You can follow me or connect with me:

Or get new content delivered directly to your inbox.

Join 4,025 other subscribers

I'm writing a book

Stack of copies of How to Hire and Manage Remote Teams

How to Hire and Manage Remote Teams, where I distill all the techniques I've been using to build and manage distributed teams for the past 10 years.

I write about:

announcement blogging book book review book reviews books building Sano Business C# Clojure ClojureScript Common Lisp database Debian Esperanto Git history idea Java Kubuntu Lisp music Non-Fiction OpenID programming Python Rails rant re-frame release Ruby Ruby on Rails Sano science science fiction security self-help Star Trek startups technology Ubuntu video web Windows WordPress

I've been writing for a while:

%d bloggers like this: