Creating dynamic queries depending on parameter passed in rails 3

Viewed 4858

Is it possible to create something cleaner out of this dynamic query:

@photos = Photo.within(100, :origin => [params[:latitude], params[:longitude]]) unless (params[:latitude].nil? || params[:longitude].nil?)

if @photos.nil? then
  conditions  = String.new
  values      = Array.new

  params.each_key do |key|

    if key == 'since_id' then
      conditions << " AND " unless conditions.length == 0
      conditions << "id > ?"
      values << params[key]
    elsif key == 'user_id' then
      conditions << " AND " unless conditions.length == 0
      conditions << "user_id = ?"
      values << params[key]
    elsif key == 'id' then
      conditions << " AND " unless conditions.length == 0
      conditions << "id = ?"
      values << params[key]
    end
  end

  values.insert(0, conditions)
  @photos = Photo.limit(15).order("created_at DESC").where(values) unless values.nil?

end
1 Answers
Related