goodjobbin85 goodjobbin85 - 1 year ago 53
Ruby Question

how to query based on boolean attribute in rails?

I'm trying to query only objects from the database whose boolean attribute "in_season" returns true and its not working.

class Item < ApplicationRecord
validates :name, presence: true, uniqueness: true
validates :price, presence: true, numericality: true
validates :quantity, presence: true, numericality: { only_integer: true }
validates :description, presence: true

def self.in_season
where("in_season = ?", "true")


class ItemsController < ApplicationController

def index
@items = Item.in_season


I feel like everything is set up correctly and I'm not getting any errors, but my index page is blank because none of the items are being queried correctly.

Answer Source

You need to fix the syntax. Your mistake is that you're passing a string "true", whereas you want to pass boolean value true.

def self.in_season
  where(in_season: true)

It's more Railsy to use scope for such needs:

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

Read more about scoping in Rails Guides on scopes.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download