user13246558
user13246558

Reputation: 41

How to select elements in the DB depending on a boolean attribute

I am running a Ruby On Rails 6.0.3.1 server with a SQLite3 database.

One of my models is called Airport and has several colums like listable which is a boolean.

I want to call Airport.listable to get all the airports that should be displayed in the list.

// app/models/airport.rb
class Airport < ActiveRecord::Base
    validates :icao, :latitude, :longitude, presence: true
    validates :icao, uniqueness: true

    has_many :departure_compagny_routes, class_name: 'CompagnyRoute', foreign_key: 'departure_id'
    has_many :arrival_compagny_routes, class_name: 'CompagnyRoute', foreign_key: 'arrival_id'

    scope :listable, -> { where(listable: true) }

    def to_param
        icao
    end

    def compagny_routes
        departure_compagny_routes + arrival_compagny_routes
    end
end

When I call Airport.listable, I get an empty list. I get the same problem when calling Airport.where(listable: true).

I recently updated my application from Rails 4.2 to Rails 6, and the code worked perfectly until then.

I have the very same problem with other models: Model.where(boolean_attribute: bool) is always empty, but calling Airport.where(iata: nil), where iata is a string, works perfectly.

How can I get rid of this and have my scope work?

Upvotes: 2

Views: 54

Answers (1)

Dan
Dan

Reputation: 1288

Have you tried:

scope :listable, -> { where(listable: 1) }

SQLite might be getting confused because it doesn't have real booleans.

https://www.sqlite.org/datatype3.html

SQLite does not have a separate Boolean storage class. Instead, Boolean values are stored as integers 0 (false) and 1 (true).

Upvotes: 4

Related Questions