5

ハイ、

私のコード:

@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

4

2 に答える 2

8

関連付け拡張を使用します。

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

編集

この特定のケースでは、関連付け関数が適切なオプションである可能性があります。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または、クラスで直接 named_scope を使用できます

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

一方、will_paginateプラグインを使用しないのはなぜですか?

于 2010-03-30T16:32:32.740 に答える
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(*)
于 2010-03-30T16:18:59.483 に答える