Shortcut for Checking Not Nil and Not Empty in Rails

Dec 02, 2025 · Programming · 12 views · 7.8

Keywords: Ruby on Rails | Ruby | present? method

Abstract: This article explains how to simplify checking for non-nil and non-empty strings in Ruby on Rails using the `present?` and `?` methods. It delves into Ruby's logical false values and provides code examples to enhance code conciseness and maintainability.

In Ruby on Rails development, it is common to check user attributes in views or controllers to avoid displaying nil or empty strings. Traditional approaches like @user.city != nil && @user.city != "" are verbose and prone to code duplication. To address this, Rails offers built-in shortcuts.

Using the present? Method

Rails' ActiveSupport library extends Ruby core classes with the present? method. This method checks if an object is not nil and not empty (for strings, empty strings or those with only spaces are considered empty). For example, in a controller:

def show 
  @city = @user.city.present? 
end

This line is equivalent to @user.city != nil && @user.city != "" but more concise. By invoking present?, developers can easily validate attributes and reduce redundancy.

ActiveRecord's ? Method

For ActiveRecord model attributes, Rails provides an even shorter ? method, which serves as an alias for present?. It can be used as follows:

def show 
  @city = @user.city? 
end

This method functions similarly to present? but with a more compact syntax, suitable for quick checks. Note that the ? method is specific to model attributes, whereas present? can be applied to any object.

Optimizing with Ruby's Logical False Values

In Ruby, the only logically false values are nil and false. Therefore, unless distinguishing between false and nil is necessary (e.g., for tri-state variables), a simple conditional can be used:

if variable 
  # execute code 
end

This is more idiomatic than if !variable.nil? or if variable != nil. However, for empty string checks, the present? method is more precise as it handles both nil and empty values.

Conclusion

By adopting the present? or ? methods, developers can efficiently manage non-empty checks in Rails applications, improving code readability and maintainability. It is recommended to prioritize these shortcuts in scenarios involving user attribute validation and leverage Ruby's logical false value properties for optimization.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.