goodjobbin85
goodjobbin85

Reputation: 111

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")
end

end

class ItemsController < ApplicationController

def index
  @items = Item.in_season
end

end

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.

Upvotes: 1

Views: 1714

Answers (1)

Andrey Deineko
Andrey Deineko

Reputation: 52377

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)
end

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.

Upvotes: 3

Related Questions