views:

371

answers:

1

I am using a new Rails project & an old established Oracle db using adapter: oracle_enhanced. Would like to be able to have dynamic searches against the db depending upon what info/field(s) is available to search against.

I am trying to get from

http://www.abc.com/order/show?acct_num=a123&po_num=789z

and create an object such as

class Order
  attr_reader :customer_name, :acct_num, :order_date, :po_num, :qty.
end

I have the paramaters from the request.query_parameters hashtable.

Now in case I am going down the wrong path what I want to do is use the query string and be able to find all orders where acct_num_in_model = acct_num_from_query_string and po_num_from_model = po_num_from_query_string etc. If something is empty such as po_number then return all that match the acct_number and if acct_num empty all that match that po. I am expecting the following:

abc.com/order/show?acct_num=a123&po_num=789z

to return all orders with acct_num=a123 and po_num=789z

abc.com/order/show?acct_num=a123 to return all orders with acct_num = a123

abc.com/order/show?po_num=789z

to return all orders with po_num = 789z

abc.com/order/show?po_num=789z&qty=6

to return all orders with po_num = 789z & qty=6

+1  A: 

Given you want to use rails, I suggest this:

QUERY_WHITELIST = ['po_num','qty','acct_num']
Order.find :all, :conditions => params.slice(*QUERY_WHITELIST)

or

QUERY_WHITELIST = ['po_num','qty','acct_num']
Order.all :conditions => params.slice(*QUERY_WHITELIST)

depending on your Rails version.

hurikhan77
when I use this solution I get ArgumentError Unknown key(s): conditons (that is the erros spelling not mine of conditions). I believe that is because if I do params.inspect I get ..."action"=>"show", "controller"=>"order"} included in the list.So I changed params.slice(*QUERY_WHITELIST) to request.query_string.slice(*QUERY_WHITELIST) because request.query_string contains only the parameters from the querystring but that gives me TypeError in OrderController#show can't convert String into Integer.So this is not working for me.
Phil Langeberg
The slice method "filters" the params, so the result no longer would contain "action" or "controller". query_string however is a string - you don't want to use that (unless you want to fiddle around with parameter parsing und unescaping). I'll try to reproduce. Check back later.
hurikhan77
What database interface do you use? My resolution is for ActiveRecord... Are you sure you spelled "conditions" right in your code? Happens to me sometimes.
hurikhan77
Phil Langeberg
For the database query it doesn't matter if you compare to the string "123" or to the integer 123... Both match. So rails passes strings anyway (from the params hash).
hurikhan77