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

Tot*_*.js 5 ruby-on-rails count limit has-many offset

HY,

我的代码:

@profile.images
Run Code Online (Sandbox Code Playgroud)

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

@profile.images(:limit => 10, :offset => 10)
Run Code Online (Sandbox Code Playgroud)

而不是这样

has_many :images, :limit => 10, :offset => 10
Run Code Online (Sandbox Code Playgroud)

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

@profile.count_images
Run Code Online (Sandbox Code Playgroud)

谢谢 (:


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
Run Code Online (Sandbox Code Playgroud)

结束

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

Har*_*tty 8

使用关联扩展:

class Profile < ActiveRecord::Base
  has_many :images do
    def page(limit=10, offset=0)
      all(:limit=> limit, :offset=>offset)
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

现在您可以使用以下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
Run Code Online (Sandbox Code Playgroud)

编辑

在这种特定情况下,关联功能可能是合适的选择.甚至带有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
Run Code Online (Sandbox Code Playgroud)

现在,您可以将此named_scope与关联一起使用:

@profile.images.paginate(2, 20).all
Run Code Online (Sandbox Code Playgroud)

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

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

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