So I want to dynamically pass filter parameters to my where method so basically I have this
@colleges = College.where(@filter).order(@sort_by).paginate(:page => params[:page], :per_page => 20)
And the @where is just a string built with this method
def get_filter_parameters
if params[:action] == 'index'
table = 'colleges'
columns = College.column_names
else
table = 'housings'
columns = Housing.column_names
end
filters = params.except(:controller, :action, :id, :sort_by, :order, :page, :college_id)
filter_keys = columns & filters.keys
@filter = ""
first = true
if filter_keys
filter_keys.each do |f|
if first
@filter << "#{table}.#{f} = '#{filters[f]}'"
first = false
else
@filter << " AND #{table}.#{f} = '#{filters[f]}'"
end
end
else
@filter = "1=1"
end
The problem is I don't know how good it is to drop raw SQL into a where method like that. I know normally you can do stuff like :state => 'PA', but how do I do that dynamically?
UPDATE
Okay so I am now passing a hash and have this:
if params[:action] == 'index'
columns = College.column_names
else
columns = Housing.column_names
end
filters = params.except(:controller, :action, :id, :sort_by, :order, :page, :college_id)
filter_keys = columns & filters.keys
@filter = {}
if filter_keys
filter_keys.each do |f|
@filter[f] = filters[f]
end
end
Will that be enough to protect against injection?