Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/delphi/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 我有很多关系,我想设置自定义限制和偏移量。还有数一数_Ruby On Rails_Count_Limit_Has Many_Offset - Fatal编程技术网

Ruby on rails 我有很多关系,我想设置自定义限制和偏移量。还有数一数

Ruby on rails 我有很多关系,我想设置自定义限制和偏移量。还有数一数,ruby-on-rails,count,limit,has-many,offset,Ruby On Rails,Count,Limit,Has Many,Offset,Hy 我的代码: @profile.images 我希望每次只得到10张图像,偏移量为10,就像这样 @profile.images(:limit => 10, :offset => 10) has_many :images, :limit => 10, :offset => 10 而不是像这样 @profile.images(:limit => 10, :offset => 10) has_many :images, :limit => 10,

Hy

我的代码:

@profile.images
我希望每次只得到10张图像,偏移量为10,就像这样

@profile.images(:limit => 10, :offset => 10)
has_many :images, :limit => 10, :offset => 10
而不是像这样

@profile.images(:limit => 10, :offset => 10)
has_many :images, :limit => 10, :offset => 10
然后我想以某种方式计算该配置文件的所有图像

@profile.count_images
谢谢(:


有很多图像,:foreign\u key=>'on\u id',:conditions=>'on\u type=“profile”do
def分页(页码=1,限制=10,偏移=nil)
如果页面<1,则页面=无
如果限值<1,则限值=1
如果(偏移量和偏移量<0)偏移量=0
如果(!第页),则偏移量为0
偏移量=限制*(第1页)如果(第页)
全部(:limit=>limit,:offset=>offset)
结束
结束


现在,我想将此行为添加到other has_许多关系中。但我不想复制粘贴代码…有什么想法吗?:p

您可以使用
来确定调用
@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(*)
Image.with_作用域(:find=>{:limit=>10,:offset=>10})do
@profile.images#使用限制和偏移加载关联
结束

@profile.images.reset#重置缓存关联,否则大小将返回使用关联扩展:

class Profile < ActiveRecord::Base
  has_many :images do
    def page(limit=10, offset=0)
      all(:limit=> limit, :offset=>offset)
    end
  end
end
编辑

在这种特定情况下,关联函数可能是一个合适的选项。即使是具有命名\u作用域的lambda也可以工作。如果在
Profile
类上定义它,则会失去
命名\u作用域的可重用方面。应在图像类上定义命名\u作用域

class Image < ActiveRecord::Base

  named_scope :paginate, lambda { |page, per_page| { :offset => ((page||1) -1) * 
                              (per_page || 10), :limit => :per_page||10 } }

end
或者您可以直接在
图像
类上使用命名的\u范围

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

另一方面,你为什么不使用这个插件?

谢谢。你给了我一个新的想法:命名为|scope:limit,lambda{num}{limit=>num}命名为|scope:offset,lambda{num}{:limit=>num},然后是@profile.images.limit(10).offset(10)谢谢,这好多了。我得到了这个,但不是很酷:命名为_scope:paginate,lambda{page,limit,offset{124;:limit=>limit | | 10,:offset=>offset | |((limit | 10)*(page-1))}真的谢谢!现在我要试试;)是的,也许使用will paginate更好。我现在就去学。无论如何,谢谢你。它可以帮助其他事情。。。
Image.paginate(2, 20).all(:conditions => ["created_at > ?" , 7.days.ago])