0

I have developed a small API that returns some minor JSON objects (mainly small resources, nothing fancy), but I am in a situation where I need to expand one of the API endpoints to return a little more than just whats there currently.

For Example - Currently, I have the following in my routes:

resources :school_types do
        resources :schools
      end

So, if a user accesses /api/v1/school_types/1/schools.json an entire listing of schools will come back based on the school_type_id

Well, I am now wanting to take it a little further and do the following: /api/v1/school_types/1/schools.json?param_1=foo&param_2=bar

So when I construct the ActiveRecord call it would dynamically generate the SQL query based on the parameters passed in.

This is what I have so far:

conditions = ""
      params.except(:controller, :format, :action).each_with_index do |value, index|
        conditions << "#{params[index]} = #{value} AND "
      end 

This is the conditions variable output: " = [\"state_id\", \"1\"] AND = [\"district_id\", \"1\"] AND = [\"school_type_id\", \"1\"] AND "

Obviously I am doing something wrong, LOL.

dennismonsewicz
  • 25,132
  • 33
  • 116
  • 189

1 Answers1

2

I would strongly suggest using a tool like MetaSearch rather than rolling your own. Your current implementation is highly subject to SQL injection attacks.

Brandan
  • 14,735
  • 3
  • 56
  • 71
  • Thanks for your reply! I am going to take a look into the gem you suggested. Would something like this work too? http://stackoverflow.com/a/6421870/282343 – dennismonsewicz Apr 20 '12 at 19:25
  • Yes. Depending on how many different parameters you need to support, it may be simpler to use custom scopes than to implement MetaSearch. The important thing is to use Rails methods to assemble the query rather than simply concatenating and interpolating strings. – Brandan Apr 20 '12 at 20:28