海蘭,我有一個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
謝謝,這樣好多了。我得到了這個,但不是很酷: named_scope:paginate,lambda {| page,limit,offset | {:limit => limit || 10,:offset => offset || ((limit || 10)*(page - 1))}} 非常感謝!現在我會嘗試一下;) – 2010-03-30 16:40:51
+1更高級的技術 – vladr 2010-03-30 16:51:29
我用一個named_scope解決方案更新了我的答案。 – 2010-03-30 17:00:38