我有一个has_many关系,我想设置自定义限制和偏移量。 以及数数

HY,

我的代码:

@profile.images 

而且我想在时间上只获得10张图像,并且像这样一个10偏移

 @profile.images(:limit => 10, :offset => 10) 

而不是这样

 has_many :images, :limit => 10, :offset => 10 

然后我想在某种程度上计算该配置文件的所有图像。

 @profile.count_images 

谢谢 (:


 has_many :images, :foreign_key => 'on_id', :conditions => 'on_type = "profile"' do def paginate(page = 1, limit = 10, offset = nil) page = nil if page < 1 limit = 1 if limit < 1 offset = 0 if(offset && offset  limit, :offset => offset) end 

结束

现在我想将此行为添加到其他has_many关系中。 但我不想复制粘贴代码……任何想法? :P

使用关联扩展:

 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 

编辑

在这种特定情况下,关联function可能是合适的选择。 甚至带有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 

或者您可以直接在Image类上使用named_scope

 Image.paginate(2, 20).all(:conditions => ["created_at > ?" , 7.days.ago]) 

另一方面,为什么不使用will_paginate插件?

您可以使用with_scope将调用范围with_scope@profile.images ,并在范围外执行计数。

 Image.with_scope(:find => { :limit => 10, :offset => 10 }) do @profile.images # load association using limit and offset end @profile.images.reset # reset cached association, else size would return <=10 @profile.images.size # go to the database again for a real COUNT(*)