范围查询中的ActiveRecord OR子句

时间:2011-09-23 22:47:38

标签: ruby-on-rails ruby activerecord

statuses = %w(sick healthy hungry)

query = User.scoped(:joins => 'left outer join pets on pets.user_id = users.id', :conditions => { 'pets.id' => nil, 'users.job_status' => stati })

鉴于上面的代码,是否可以向:conditions添加一个OR子句来表示类似

的内容
where (pets.id is NULL AND users.status IN ('sick', 'healthy', 'hungry')) OR (users.gender = 'male')

2 个答案:

答案 0 :(得分:0)

您可以使用MetaWhere gem

执行以下操作
statuses = %w(sick healthy hungry)

query = User.include(:pets).where(
  ('pets.id' => nil, 'users.job_status' => statuses) |
  ('users.gender' => 'male')
)

|符号用于OR条件。

PS include指令使用LEFT OUTER JOIN,因此无需手动编码JOIN。

答案 1 :(得分:0)

您可以使用SQL条件而不是哈希条件:

query = User.scoped(
    :joins => 'left outer join pets on pets.user_id = users.id',
    :conditions => [
        '(pets.id is null AND users.status IN (?)) OR (users.gender = ?)',
        statuses, 'male'
    ]
)

或者:

query = User.scoped(
    :joins => 'left outer join pets on pets.user_id = users.id',
    :conditions => [
        '(pets.id is null AND users.status IN (:statuses)) OR (users.gender = :gender)',
        { :status => statuses, :gender => 'male' }
    ]
)

缺点是您必须避免手动尝试pets.is = NULL