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
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With