ActiveRecord OR clause in scoped query

与世无争的帅哥 提交于 2020-01-06 14:19:40

问题


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 })

Given the code above, is it possible to add an OR clause to the :conditions to say something like

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

回答1:


You can do the following using the MetaWhere gem

statuses = %w(sick healthy hungry)

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

The | symbol is used for OR condition.

PS : The include directive uses LEFT OUTER JOIN so there is no need to hand code the JOIN.




回答2:


You could use an SQL condition instead of a Hash condition:

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'
    ]
)

Or:

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' }
    ]
)

The downside is that you have to avoid trying pets.is = NULL by hand.



来源:https://stackoverflow.com/questions/7535592/activerecord-or-clause-in-scoped-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!