Rails 5 adds ActiveRecord or

Here’s a long awaited feature that is added in Rails 5: ActiveRecord or.

Previously you had to use ARel or resort to a SQL snippet:

Flower.where('smell = ? OR color = ?', 'nice', 'bright')

# => SELECT "flowers".* FROM "flowers" WHERE (smell = 'nice' OR color = 'bright')

Now you can do:

Flower.where(smell: 'nice').or(Flower.where(color: 'bright'))

# => SELECT "flowers".* FROM "flowers" WHERE ("flowers"."smell" = ? OR "flowers"."color" = ?)  [["smell", "nice"], ["color", "bright"]]

In other words: you first build a relation, then use the or method on it passing in as an argument another relation. These two relations must be “structurally compatible”: scoped on the same model, and not using limit, offset or uniq. You can see what you can and can’t do with this in more detail by looking at the test cases.

More details at the commit or the PR.

This entry was posted in Technology and tagged , , . Bookmark the permalink. Trackbacks are closed, but you can post a comment.

Post a Comment

Your email is never published nor shared. Required fields are marked *

You may use these HTML tags and attributes <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

*
*

Time limit is exhausted. Please reload the CAPTCHA.