2010-03-30 31 views
4

海蘭,我有一個has_many關係,我想設置自定義限制和偏移量。還有指望他們

我的代碼:

@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

回答

7

使用聯想擴展:

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 

編輯

在這種特定的情況下,聯想功能可能做個合適的人ption。即使lambda與named_scope可能工作。如果你在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

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

使用named_scope在另一方面,你爲什麼不使用will_paginate插件?

+1

謝謝,這樣好多了。我得到了這個,但不是很酷: named_scope:paginate,lambda {| page,limit,offset | {:limit => limit || 10,:offset => offset || ((limit || 10)*(page - 1))}} 非常感謝!現在我會嘗試一下;) – 2010-03-30 16:40:51

+0

+1更高級的技術 – vladr 2010-03-30 16:51:29

+0

我用一個named_scope解決方案更新了我的答案。 – 2010-03-30 17:00:38

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(*) 
+0

謝謝。你給了我一個新的想法: named_scope:limit,lambda {| num | {:limit => num}} named_scope:offset,lambda {| num | {:limit => num}} 然後 @ profile.images.limit(10).offset(10) – 2010-03-30 16:35:42

相關問題