Swati Aggarwal
Swati Aggarwal

Reputation: 1275

Rails - Fetch results on the basis of number of params in query string

I am working on an events application where i want to filter events depending on the 3 parameters location or starts_at or ends_at in the query string. There can be any one, two or all the parameters in the query string. In i use if-else statement i need to make 6 cases which will make my code clumsy. Rather i am thinking to implement something this way:

class EventsController < ApplicationController
  def index
    unless params.empty?
      unless params[:location].nil?
        @events = Event.where("location = ?", params[:location])       
      end

       unless params[:starts_at].nil?
         unless @events.empty?
           @events = @events.where("start_date = ?", params[:start_date])      
         else
           @events = Event.where("Date(starts_at) = Date(?)", params[:starts_at])
         end
       end
       unless params[:ends_at].nil?
         unless @events.empty?
           @events = @events.where("end_date = ?", params[:end_date])      
         else
           @events = Event.where("Date(ends_at) = Date(?)", params[:ends_at])
         end
       end
    end
  end
end 

But this code doesnt work since where query doen not work on an array. Can someone suggest me some solution for this..

Upvotes: 0

Views: 162

Answers (2)

Brandan
Brandan

Reputation: 14983

You should be able to pass your params hash directly to where, and it will form the correct SQL based on the keys and values of that hash:

Event.where(params)

An example in the console:

1.9.3p194 :001 > puts Example.where(:location => 'here', :started_at => '2012-08-13').to_sql
SELECT "examples".* FROM "examples"  WHERE "examples"."location" = 'here' AND "examples"."started_at" = '2012-08-13'

Upvotes: 2

Salil
Salil

Reputation: 47472

Try Following

  def index
    unless params.empty?
      where_array, arr = [], []
      if params[:location]
        where_array << "location = ?"
        arr << params[:location]
      end
      if params[:starts_at]
        where_array << "start_date = ?"
        arr << params[:starts_at]
      end
      if params[:ends_at]
        where_array << "end_date = ?"
        arr << params[:ends_at]
      end
       @events = arr.blank? ? [] : Event.where([where_array.join(" AND "), *arr])
    end
  end

Upvotes: 0

Related Questions