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')
答案 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
。