简体   繁体   中英

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM