ruby-on-rails – 我有一个has_many关系,我想设置自定义限制和偏
发布时间:2020-12-17 02:50:52 所属栏目:百科 来源:网络整理
导读:HY, 我的代码: @profile.images 而且我想在时间上只获得10张图像,并且像这样一个10偏移 @profile.images(:limit = 10,:offset = 10) 而不是这样 has_many :images,:limit = 10,:offset = 10 然后我想在某种程度上计算该配置文件的所有图像. @profile.count_
HY,
我的代码: @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 解决方法
使用关联扩展:
class Profile < ActiveRecord::Base has_many :images do def page(limit=10,offset=0) all(:limit=> limit,:offset=>offset) end end end 现在您可以使用页面方法,如下所示: @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的lambda也可以工作.如果在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插件? (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |