如何将此查询转换为ActiveRecord(第5条)

时间:2019-03-18 22:42:25

标签: sql ruby-on-rails activerecord ruby-on-rails-5

我有一个如下的SQL查询:

SELECT user_id, group_id
    FROM boats
    WHERE is_docked = 1
    AND (
      dock_id IS NULL
      OR
      dock_2_id IS NULL
    )

我在ActiveRecord中最接近的方法是:

Boat.where(is_docked: 1).where(dock_id: nil).or(Boat.where(dock_id_2:nil))

从上面生成的SQL语法不是我所期望的。正确的方法是什么?

1 个答案:

答案 0 :(得分:0)

Boat.where('is_docked = ? AND (dock_id IS NULL OR dock_2_id IS NULL)', 1,).select(:property_id, :player_id)

更新船模

class Boat < ApplicationRecord
  scope :docked, -> { where('is_docked = ?', 1 }
  scope :with_unassigned_dock, -> { where('dock_id IS NULL OR dock_2_id IS NULL') }
end

新查询

Boat.docked.with_unassigned_dock.select(:property_id, :player_id)