我正在创建一个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。任何帮助或解释都非常感谢。
答案 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'