我可以传递多个参数来获得多个结果

时间:2017-08-09 06:13:58

标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-4 ruby-on-rails-3.2

我正在创建一个API,其中有一个名为发票的表,其中 customerType 是一列。 customerType 只能是四个可能的值 IE。 PCT,RVN,INT或OTH。

现在,我想传递以下网址:

http://localhost:3000/api/quatertodate?group-by=customerNumber&customertype=RVN,INT
http://localhost:3000/api/quatertodate?group-by=customerNumber&customertype=RVN,INT,OTH
http://localhost:3000/api/quatertodate?group-by=customerNumber
http://localhost:3000/api/quatertodate?group-by=customerNumber&customertype=PCT
http://localhost:3000/api/quatertodate?group-by=customerNumber&customertype=INT,PCT

但是,问题是每当我传递单个 customertype 或根本没有 customertype 时,它都可以工作,但只要我在 customertype 当它应该通过执行内部 OR 查询返回它们的组合结果时,它返回 null

controller index 方法中,我有:

def index
    @invoices=if params[:'group-by'].present?
        if params[:'group-by'].to_s == "customerNumber" 

            if params[:customertype].present?
                Invoice.where(customerType: params[:customertype])
            else
                Invoice.order('customerNumber')
            end
        end
    end 
    render json: {status: 'SUCCESS', messasge: 'LOADED QUATERLY INVOICES', data: @invoices}, status: :ok
end

注意:我能找到的最接近的答案是StackOverflow Link。任何帮助或解释都非常感谢。

1 个答案:

答案 0 :(得分:1)

那是因为您尝试查询Invoice customerType等于RVN,INT

您可能需要在split参数上执行customertype

def index
    @invoices=if params[:'group-by'].present?
        if params[:'group-by'].to_s == "customerNumber" 

            if params[:customertype].present?
                Invoice.where(customerType: params[:customertype].split(","))
            else
                Invoice.order('customerNumber')
            end
        end
    end 
    render json: {status: 'SUCCESS', messasge: 'LOADED QUATERLY INVOICES', data: @invoices}, status: :ok
end

这将为您生成一个查询:

SELECT `invoices`.* FROM `invoices` WHERE `invoices`.`customerType` IN ('RVN', 'INT')

而不是:

SELECT `invoices`.* FROM `invoices` WHERE `invoices`.`customerType` = 'RVN,INT'