Ruby on rails 作用域查询中的ActiveRecord或子句

Ruby on rails 作用域查询中的ActiveRecord或子句,ruby-on-rails,ruby,activerecord,Ruby On Rails,Ruby,Activerecord,根据上面的代码,是否可以在:conditions中添加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 }) 您可以使用gem执行以下操作 |符号用

根据上面的代码,是否可以在
:conditions
中添加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 })

您可以使用gem执行以下操作

|
符号用于
条件


PS:指令
include
使用
左外联接
,因此无需手动编码联接。

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

statuses = %w(sick healthy hungry)

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

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

statuses = %w(sick healthy hungry)

query = User.include(:pets).where(
  ('pets.id' => nil, 'users.job_status' => statuses) |
  ('users.gender' => 'male')
)
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' }
    ]
)