dennismonsewicz
dennismonsewicz

Reputation: 25542

Rails 3: Looping through parameters for dynamic based MySQL query

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.

Upvotes: 0

Views: 364

Answers (1)

Brandan
Brandan

Reputation: 14983

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

Upvotes: 2

Related Questions