Rails 5 adds OR Activerecord method

This or method was introduced in Rails 5, It returns a new ActiveRecord::Relation which is logical union or two relations.


  Post.where("id = 1").or(Post.where("author_id = ?", 66))
  => SELECT `posts`.* FROM `posts` WHERE ((id = 1) OR (author_id = 66))

Note: The two relations must be structurally compatible, i.e they must scope same model.

Combining OR with Scope

ActiveRecord or can be used along with the defined scope in the model.


  class Post < ApplicationRecord
    scope :active, -> { where(active: true) }

  Post.active.or(Post.where("id = ?", 66))
  => returns all Posts where Post are active or Post id is 66

Reference #Pull Request

Recommended Posts

Descendants vs Subclasses in Ruby
Descendants has been a part of Rails ActiveSupport::DescendantsTracker for quite a while. However, Class#subsclasses is...
Ruby 3.1 adds subclasses method
Ruby 3.1 adds Class#subclasses method, which returns an array of subclasses directly inheriting from the...
How to query records which has missing associations in Rails 6
Rails 6 provides a simpler way to query the records which does not have any...