1

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.

1
  • You are asking about a boolean but passing a string for your comparison. where("in_season = ?", true) or where(in_season: true) should work for you. Commented May 8, 2017 at 21:59

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.