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
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'
region = params[:state].presence || params[:country].presence || 'US'
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:
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 %>
presence we can make this code shorter but still readable.
<%= render @users.presence || 'no_results' %>
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)