Use association extensions:
class Profile < ActiveRecord::Base
has_many :images do
def page(limit=10, offset=0)
all(:limit=> limit, :offset=>offset)
end
end
end
Now you can use the page
method as follows:
@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
In this specific case, association function might be a suitable option. Even lambda with named_scope might work. If you define it on the Profile
class you are loosing the reusable aspect of the named_scope
. You should define the named_scope on your image class.
class Image < ActiveRecord::Base
named_scope :paginate, lambda { |page, per_page| { :offset => ((page||1) -1) *
(per_page || 10), :limit => :per_page||10 } }
end
Now you can use this named_scope with the association:
@profile.images.paginate(2, 20).all
Or you can use the named_scope directly on the Image
class
Image.paginate(2, 20).all(:conditions => ["created_at > ?" , 7.days.ago])
On the other hand why are not using the will_paginate plugin?