<body><script type="text/javascript"> function setAttributeOnload(object, attribute, val) { if(window.addEventListener) { window.addEventListener('load', function(){ object[attribute] = val; }, false); } else { window.attachEvent('onload', function(){ object[attribute] = val; }); } } </script> <div id="navbar-iframe-container"></div> <script type="text/javascript" src="https://apis.google.com/js/plusone.js"></script> <script type="text/javascript"> gapi.load("gapi.iframes:gapi.iframes.style.bubble", function() { if (gapi.iframes && gapi.iframes.getContext) { gapi.iframes.getContext().openChild({ url: 'https://www.blogger.com/navbar.g?targetBlogID\x3d4684235500622716427\x26blogName\x3dCaiwangqin\x27s+blog\x26publishMode\x3dPUBLISH_MODE_HOSTED\x26navbarType\x3dBLUE\x26layoutType\x3dCLASSIC\x26searchRoot\x3dhttp://blog.caiwangqin.com/search\x26blogLocale\x3dzh_CN\x26v\x3d2\x26homepageUrl\x3dhttp://blog.caiwangqin.com/\x26vt\x3d3393395200455623441', where: document.getElementById("navbar-iframe-container"), id: "navbar-iframe" }); } }); </script>

Caiwangqin's blog

Focus on Cloud Service, Smart Hardware, Architecture, Technic and beyond…

为find_by_sql增加paginate功能

2007年7月13日星期五

在RubyonRails编程时,很多时候为find_by_sql增加paginate功能显得很有用,BOGLE已经实现了一个无关数据库的paginate_by_sql for Rails, 试用后感觉不错。代码如下:



# 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, :o 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 %> <br>
<% end %>






Del.icio.us :


标签:

posted by Jesse Cai, 下午1:04

0 Comments:

发表评论

订阅 帖子评论 [Atom]

<< 主页