字体: | 推荐给好友 上一篇 | 下一篇

为find_by_sql增加paginate功能-Ruby开发者

发布: 2007-8-10 10:15 | 作者: skyover | 来源: | 查看: 48次

# paginate by sql

# added support for sql with arguments

# added a :count option for passing in either a Integer count

# or count query.

module ActiveRecord

class Base

def self.find_by_sql_with_limit(sql, offset, limit)

sql = sanitize_sql(sql)

add_limit!(sql, {:limit => limit, ffset => offset})

find_by_sql(sql)

end

def self.count_by_sql_wrapping_select_query(sql)

sql = sanitize_sql(sql)

count_by_sql(”select count(*) from (#{sql})”)

end

end

end

class ApplicationController < ActionController::Base

def paginate_by_sql(model, sql, per_page, options={})

if options[:count]

if options[:count].is_a? Integer

total = options[:count]

else

total = model.count_by_sql(options[:count])

end

else

total = model.count_by_sql_wrapping_select_query(sql)

end

object_pages = Paginator.new self, total, per_page,

@params[’page’]

objects = model.find_by_sql_with_limit(sql,

object_pages.current.to_sql[1], per_page)

return [object_pages, objects]

end

end 在Controller中的使用如下:

sql = "select j.id, j.name,c.name as company_name from jobs j

inner join companies on j.company_id=c.id

order by j.activated_date DESC”

@job_pages, @jobs = paginate_by_sql Job, sql, 20

在View中使用如下:

<%= pagination_links @job_pages %>

<% for job in jobs %>

<%= job.name %> <%= job.company_name %>

<% end %>

我来说两句

内容:

验证:

发表评论

最新评论

删除 Guest  post at 2007-11-09 17:57:36
5

查看全部评论……(共1条)

 

评分:0

我来说两句

seccode