Creating dynamic queries depending on the parameter passed in rails 3

Is it possible to create something cleaner from 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 
+8
activerecord ruby-on-rails-3
source share
1 answer

I think the right way to do this is to use areas

 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 the 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) 
+14
source share

All Articles