Solution: Getting will_paginate and acts_as_taggable to play nice

I’m using both will_paginate and acts_as_taggable plugins on the app I’m working on. The tagged results need to be paged just like other lists. Here’s my hack to get the two to work together:

RAILS_ROOT/lib/paginated_tags.rb in lib:

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

    def find_tagged_with(list,*args)

      #build the limit sql
      options = args.last.is_a?(Hash) ? args.pop.symbolize_keys : {}
      limit,offset = options.delete(:limit), options.delete(:offset) unless options.empty?
      scope =  (limit && offset) ? "LIMIT #{offset}, #{limit}" : ""

      find_by_sql([
        "SELECT #{table_name}.* FROM #{table_name}, tags, taggings " +
        "WHERE #{table_name}.#{primary_key} = taggings.taggable_id " +
        "AND taggings.taggable_type = ? " +
        "AND taggings.tag_id = [tags.id](http://tags.id) AND [tags.name](http://tags.name) IN (?) #{scope}",
        acts_as_taggable_options[:taggable_type], list

      ])
     
    end
    #will_paginate will call find_all_tagged_with
    alias find_all_tagged_with find_tagged_with
  end     
end

end end

I can now call a method like this:

@stories = Story.paginate_tagged_with(“goo”, :total_entries => 2, :page => params[:page])

You have to manually pass in the total_entries, but hacking the code where total_entries is set in the will_paginate finder method could get around this.

  • Nathan Verni