根据rails 3中传递的参数创建动态查询

时间:2011-06-21 01:42:09

标签: ruby-on-rails-3 activerecord

是否可以通过此动态查询创建更干净的东西:

@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 个答案:

答案 0 :(得分:15)

我认为正确的方法是使用范围

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 }

稍后搜索

@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)