作用域查询中的ActiveRecord OR子句
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')
您可以使用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代码。
您可以使用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
手动。