acts_as_taggable_on_steroids 与 will_paginate 的整合



使用 acts_as_taggable_on_steroids 之后经常找有某个 tag 的 item:

    @items = Item.find_tagged_with(”tag”)

找到很多需要分页显示,于是顺利成章的在后面加上:

    @items = Item.find_tagged_with(”tag”).paginate :page => paramsp[:page] || 1, :per_page => 20

发现无效!原因是 find_tagged_with 返回的是 Array,will_paginate 强大的分页功能瞬时歇菜。

于是乎整合一下两者:

    module ActiveRecord
    module Acts #:nodoc:
    module Taggable #:nodoc:
    module SingletonMethods

    def count_tagged_with(*args)
    options = find_options_for_find_tagged_with(*args)
    options.blank? ? 0 : count(”#{table_name}.id”, options.merge(:select => nil, :distinct => true))
    end

    def _paginate_tagged_with(tags, options = {})
    page, per_page = wp_parse_options!(options)
    offset = (page.to_i - 1) * per_page
    count = count_tagged_with(tags, options)
    options.merge!(:offset => offset, :limit => per_page.to_i)
    items = find_tagged_with(tags, options)
    returning WillPaginate::Collection.new(page, per_page, count) do |p|
    p.replace items
    end
    end

    end
    end
    end
    end

之后调用

    @items = Item.paginate_tagged_with tag, :page => paramsp[:page] || 1, :per_page => 20

 

你可能感兴趣的:(ActiveRecord)