لدي علاقات has_many وأريد تعيين حد مخصص وإزاحة. وكذلك لحسابهم

StackOverflow https://stackoverflow.com/questions/2546702

سؤال

هاي ،

رمز بلدي:

@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 الأخرى. لكني لا أرغب في نسخ لصق الرمز ... أي فكرة؟ : ص

هل كانت مفيدة؟

المحلول

استخدام ملحقات الجمعية:

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

تعديل

في هذه الحالة المحددة ، قد تكون وظيفة الارتباط خيارًا مناسبًا. حتى Lambda مع name_scope قد تعمل. إذا حددته على Profile الفصل الذي تفقده الجانب القابل لإعادة الاستخدام من named_scope. يجب عليك تحديد اسمه _scope على فئة الصور الخاصة بك.

class Image < ActiveRecord::Base

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

end

الآن يمكنك استخدام هذا اسمه _scope مع الجمعية:

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

أو يمكنك استخدام named_scope مباشرة على Image صف دراسي

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

من ناحية أخرى ، لماذا لا تستخدم will_paginate توصيل في؟

نصائح أخرى

يمكنك استخدام 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(*)
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top