简体   繁体   中英

How to translate this query into ActiveRecord (Rails 5)

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

Update Boat Model

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

new query

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM