I have an SQL query like the following:
SELECT user_id, group_id
FROM boats
WHERE is_docked = 1
AND (
dock_id IS NULL
OR
dock_2_id IS NULL
)
The closest I got to doing it in ActiveRecord is:
Boat.where(is_docked: 1).where(dock_id: nil).or(Boat.where(dock_id_2:nil))
The SQL syntax generated from the above isn't what I expected. What's the right way to do it?
Boat.where('is_docked = ? AND (dock_id IS NULL OR dock_2_id IS NULL)', 1,).select(:property_id, :player_id)
Or
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.