Creating dynamic queries depending on parameter passed in rails 3

前端 未结 1 1108
萌比男神i
萌比男神i 2021-01-12 02:41

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

@photos = Photo.within(100, :origin => [params[:latitude], params[:longitude]]) unl         


        
1条回答
  •  礼貌的吻别
    2021-01-12 03:08

    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)
    

    0 讨论(0)
提交回复
热议问题