我有一个如下的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语法不是我所期望的。正确的方法是什么?
答案 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)