使用关联扩展:
class Profile < ActiveRecord::Base
has_many :images do
def page(limit=10, offset=0)
all(:limit=> limit, :offset=>offset)
end
end
end
现在您可以使用page
方法如下:
@profile.images.page # will return the first 10 rows
@profile.images.page(20, 20) # will return the first 20 rows from offset 20
@profile.images # returns the images as usual
Edit
在这种特定情况下,关联函数可能是一个合适的选择。即使带有named_scope 的lambda 也可以工作。如果您将其定义在Profile
类你失去了可重用的方面named_scope
。您应该在图像类上定义named_scope。
class Image < ActiveRecord::Base
named_scope :paginate, lambda { |page, per_page| { :offset => ((page||1) -1) *
(per_page || 10), :limit => :per_page||10 } }
end
现在您可以将这个named_scope与关联一起使用:
@profile.images.paginate(2, 20).all
或者你可以直接使用named_scopeImage
class
Image.paginate(2, 20).all(:conditions => ["created_at > ?" , 7.days.ago])
另一方面,你为什么不使用将分页 http://wiki.github.com/mislav/will_paginate/插入?