Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating dynamic queries depending on parameter passed in rails 3

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
like image 933
Pier-Olivier Thibault Avatar asked Jun 21 '11 01:06

Pier-Olivier Thibault


Video Answer


1 Answers

I think the right way to do it is use scopes

scope :older_than, lambda { |value| where('id > (?)', value) if value }
scope :with_id, lambda { |value| where('id = (?)', value) if value }
scope :for_user, lambda { |value| where('user_id = (?)', value) if value }

later in search

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

@photos = Photo.with_id( params[ :id ] )
               .older_than( params[ :since_id ] )
               .for_user( params[ :user_id ] )
               .order("created_at DESC")
               .limit(15)
like image 96
Bohdan Avatar answered Sep 27 '22 20:09

Bohdan