我有一个has_many关系,我想设置自定义限制和偏移。以及计算它们 [英] I have a has_many relationships and I want to set custom limit and offset. as well as to count them

查看:172
本文介绍了我有一个has_many关系,我想设置自定义限制和偏移。以及计算它们的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Hy,

我的代码:

@profile.images

,我想得到只有10图像的时间和10偏移, / p>

and i would like to get only 10 images at time and with a 10 offset, like this

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

而不是这样

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

然后我想要查看该个人资料的所有图片。

Then I would like to count in someway all the images for that profile.

@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

end

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

Now I would like to add this behaviour to other has_many relationships. But I would not like to copy paste the code... Any idea? :P

推荐答案

使用关联扩展:

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

编辑

在这种特定情况下,关联功能可能是一个合适的选项。甚至lambda与named_scope可能工作。如果你在 Profile 类中定义它,你将失去 named_scope 的可重用方面。您应该在图像类上定义named_scope。

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

named_scope与关联:

Now you can use this named_scope with the association:

@profile.images.paginate(2, 20).all

或者可以直接在 Image class

Or you can use the named_scope directly on the Image class

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

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

On the other hand, why are you not using the will_paginate plugin?

这篇关于我有一个has_many关系,我想设置自定义限制和偏移。以及计算它们的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆