0

I am creating an API where I have a table named invoices where customerType is a column. customerType can be of only four possible values IE. PCT, RVN, INT or OTH.

Now, I want to pass URLs like:

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

But, the issue is whenever I pass a single customertype or no customertype at all, it works but whenever I pass multiple parameters in customertype it returns null when it should be returning combined result of those by performing internal OR query.

In index method of controller I have:

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

NOTE: The closest answer I could find is StackOverflow Link. Any help or explanation is much appreciated.

BlackBeard
  • 10,246
  • 7
  • 52
  • 62

1 Answers1

1

That's because you're trying to query Invoice where customerType equals RVN,INT

You might need to perform split on the customertype param:

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

This will generate for you a query:

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

Instead of:

SELECT `invoices`.* FROM `invoices` WHERE `invoices`.`customerType` = 'RVN,INT'
Igor Drozdov
  • 14,690
  • 5
  • 37
  • 53