How to Use the Rails present? Method

09/24/2021

Contents

In this article, you will learn how to use the Rails present? method.

Using the present? method

The present? method in Ruby on Rails is a convenient way to check whether an object is not nil and not blank. It returns true if the object is present, and false otherwise.

To use the present? method, you can call it on any object in your Rails application. Here are some examples:

# Check if a string is present
"hello".present?  # true

# Check if an empty string is present
"".present?  # false

# Check if a nil value is present
nil.present?  # false

# Check if an array is present
[1, 2, 3].present?  # true

# Check if an empty array is present
[].present?  # false

In addition to checking individual objects, you can also use the present? method in conditional statements. For example:

if @user.present?
  # Do something with @user
else
  # @user is nil or blank
end

You can also use the present? method with ActiveRecord models to check if a record exists in the database:

if Post.where(id: 1).present?
  # The Post with id 1 exists
else
  # The Post with id 1 does not exist
end

Another common use case for present? is in Rails views to check if a variable is present before rendering it:

<% if @user.present? %>
  <p>Welcome, <%= @user.name %></p>
<% end %>