How to Use the Rails presence Method

09/24/2021

Contents

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

Using the presence method

The Rails presence method is a convenient way to check if a value is not blank. It is available on strings, arrays, and hashes in Rails.

The presence method returns the receiver if it is present, otherwise it returns nil. A value is considered to be present if it is not blank. In Ruby, blank values are nil, false, empty strings, and empty arrays and hashes.

Here are some examples of how to use the presence method in Rails:

Strings
name = "John Doe"
if name.present?
  # Do something with the name
else
  # Handle the case where the name is blank
end
Arrays
names = ["John Doe", "Jane Smith", ""]
present_names = names.reject(&:blank?)
# => ["John Doe", "Jane Smith"]
 
name = names.first.presence || "Anonymous"
# => "John Doe"
Hashes
params = { name: "John Doe", email: "", phone: "1234567890" }
present_params = params.select { |_, v| v.present? }
# => { name: "John Doe", phone: "1234567890" }
 
email = params[:email].presence || "No email provided"
# => "No email provided"

As you can see from these examples, the presence method can be used to check if a value is present and handle it accordingly. It is especially useful when dealing with user input, where you want to make sure that required fields are not left blank.