DEV Community

Edward Loveall
Edward Loveall

Posted on

The Rails presence Method

Note: This article was originally written at https://blog.edwardloveall.com/rails-presence-method

Rails has a convenient method that I discovered the other day: presence. All it does is return itself if present?. It's a pretty simple method:

def presence
  self if present?
end
Enter fullscreen mode Exit fullscreen mode

The documentation has a great example that simplifies this:

state   = params[:state]   if params[:state].present?
country = params[:country] if params[:country].present?
region  = state || country || 'US'
Enter fullscreen mode Exit fullscreen mode

to this:

region = params[:state].presence || params[:country].presence || 'US'
Enter fullscreen mode Exit fullscreen mode

Here's another use case. Imagine your app has a page where you can search for users. There's a show.html.erb template, and two partials: user.html.erb and no_results.html.erb.

Your controller will search for users and assign them to an instance variable. If no users were found, we'd rather show the no_results partial instead of a blank page:

<% if @users.present? %>
  <%= render @users %>
<% else %>
  <% render 'no_results' %>
<% end %>
Enter fullscreen mode Exit fullscreen mode

With presence we can make this code shorter but still readable.

<%= render @users.presence || 'no_results' %>
Enter fullscreen mode Exit fullscreen mode

Most of the time present? is probably what you're looking for, but sometimes presence really cleans up your code. Keep it in mind.

Top comments (0)