5

嗨,

我的代码:

@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 < 0)
  offset = 0 if (!page)
  offset = limit * (page - 1) if (page)

  all(:limit=> limit, :offset => offset)
end

结尾

现在我想将此行为添加到其他 has_many 关系中。但我不想复制粘贴代码......知道吗?:P

4

2 回答 2

8

使用关联扩展:

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

编辑

在这种特定情况下,关联函数可能是一个合适的选项。甚至带有 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插件?

于 2010-03-30T16:32:32.740 回答
1

您可以使用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(*)
于 2010-03-30T16:18:59.483 回答