【问题标题】:Sinatra API params from URL来自 URL 的 Sinatra API 参数
【发布时间】:2013-12-06 05:08:41
【问题描述】:

我构建了一个基本的 Sinatra/Mongodb 支持的 API,并试图弄清楚如何根据通过 URL 传递的参数过滤结果。

我的产品类别:

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

我当前的路线显示所有产品:

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

如何根据用户发送的参数过滤显示的产品。例如,如果请求的 url 是 localhost:9292/products/&bundle=1 我只想显示 bundle 为 true 的产品,或者如果请求的 url 是 localhost:9292/products/&bundle=1&var=0 我想显示 bundle 为 true 且 var 为 false 的产品。

【问题讨论】:

    标签: ruby api mongodb sinatra


    【解决方案1】:

    只需使用链接:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-02-27
      • 1970-01-01
      • 1970-01-01
      • 2014-03-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多