Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

paginate on custom sql queries in rails (See related posts)

Someone in #rubyonrails wrote this. Forget who!

def paginate_from_sql(model, sql, total, per_page)
  @object_pages = Paginator.new self, total, per_page, @params['page']
  @objects = model.find_by_sql(sql + " LIMIT #{per_page} " +
                               "OFFSET #{@object_pages.current.to_sql[1]}")
end

Comments on this post

memetick posts on Jan 23, 2006 at 22:39
You can also simply add a :conditions parameter to your paginate call (similar to the find call), with your query.
saimon posts on Jun 13, 2006 at 11:52
I've modified this to automatically create the instance variables related to the supplied model.

e.g. paginate_from_sql(Artist, sql, count_sql, 10) will generate @artists & @artist_pages
    def paginate_from_sql(model, sql, count_sql, per_page)
      plural_model_name = "@#{model.name.underscore.pluralize}".to_sym
      paginator_name = "@#{model.name.underscore}_pages".to_sym
      self.instance_variable_set(paginator_name, Paginator.new(self, model.count_by_sql(count_sql), per_page, @params['page']))
      self.instance_variable_set(plural_model_name, model.find_by_sql(sql + " LIMIT #{per_page}" + " OFFSET #{self.instance_variable_get(paginator_name).current.to_sql[1]}"))
    end

You need to create an account or log in to post comments to this site.


Click here to browse all 4863 code snippets

Related Posts