Yogzzz
Yogzzz

Reputation: 2785

Sinatra API params from URL

I built a basic Sinatra/Mongodb backed API, and am trying to figure out how to filter results based on params passed into through the URL.

My Product class:

class Product
    include Mongoid::Document
    include Mongoid::Timestamps
  field :p_id, type: Integer
  field :_id, type: Integer, default: -> { p_id }
  field :title, type: String
  field :price, type: BigDecimal
  field :url, type: String
  field :upc, type: Integer
  field :bundle, type: Boolean
  field :var, type: Boolean
end

My current route displaying all products:

#localhost:9292/products
get '/products' do
  @products = Product.all
  rabl :products
end

How can I filter what products are displayed based on what params the user sends. For example, if the url requested is localhost:9292/products/&bundle=1 I want to show only products where bundle is true, or if the requested url is localhost:9292/products/&bundle=1&var=0 I want to display products where bundle is true and var is false.

Upvotes: 0

Views: 466

Answers (1)

NARKOZ
NARKOZ

Reputation: 27921

Just use chaining:

@products = Product.all
@products = @products.where(bundle: true) if params[:bundle] == '1'
@products = @products.where(var: false) if params[:var] == '0'

Upvotes: 1

Related Questions