Ivan Kataitsev
Ivan Kataitsev

Reputation: 537

Two arrays of conditions in single ActiveRecord 'where' clause

Let's say I have two pairs of SQL conditions like these:

a = [ "users.accepted = ? AND users.active_at > ?", true,  Time.zone.now ]
b = [ "users.accepted = ? AND users.active_at > ?", false, Time.zone.now + 3.days ]

I can use code like User.where(a) to get all rows that satisfy the a condition. How can I use where to get rows that satisfy either a or b conditions? The result should be ActiveRecord::Relation.

Upvotes: 0

Views: 344

Answers (1)

user483040
user483040

Reputation:

There are a couple ways to go about this.

  1. get meta_where or squeel depending upon your rails version. These are really great gems that enhance the Arel behavior of ActiveRecord::Relation.

  2. write sql manually and pass it into the where method as a string. You might have to mess with sql injection more manually, but from your example above I didn't see any incoming values that were user generated strings.

Upvotes: 2

Related Questions