Tuesday, July 9, 2013

rails_admin with will_paginate undefined method `per'

So, I was going a bit crazy yesterday while working with the rails_admin gem. When I would click on my Users model, it would complain that I had an undefined method 'per'. Or, more specifically, the following:
NoMethodError (undefined method `per' for #<ActiveRecord::Relation::ActiveRecord_Relation_User:0x007fc945ba2b40>):
So, I did my usual rounds, searching Google and checking with the folks in the Rails IRC channel. It sounded like something related to pagination, but I hadn't touched anything that rails_admin would use related to pagination. I *had* added the will_paginate gem, so I tried commenting out the code I'd added to that, to no avail. Eventually, I got around to commenting out the will_paginate gem in my Gemfile, and voila! The error disappeared, and rails_admin worked as expected. Baffled, I added will_paginate to my search, and ran across this link. I added the work-around posted by @jackquack to config/initializers/will_paginate.rb:

(Note: Check updated code further down)
if defined?(WillPaginate)
  module WillPaginate
    module ActiveRecord
      module RelationMethods
        alias_method :per, :per_page
        alias_method :num_pages, :total_pages
        alias_method :total_count, :count
      end
    end
  end
end

I then uncommented the will_paginate code that I had commented out and cross my fingers. To my relief, upon booting up the server and going back in to rails_admin, everything was working!

So I decided to post about it in hopes of relieving someone else's /facedesk'ing :]

// Update 6/2017 I have just run into another issue a new issue with this solution:

! Unable to load application: NameError: undefined method `per_page' for module `WillPaginate::ActiveRecord::RelationMethods'

So the further solution that I have come across is to wrap the code in an ActiveSupport on_load block:
if defined?(WillPaginate)
  ActiveSupport.on_load :active_record do
    module WillPaginate
      module ActiveRecord
        module RelationMethods
          alias_method :per, :per_page
          alias_method :num_pages, :total_pages
        end
      end
    end
  end
end

9 comments:

  1. Thank you, I had the same problem, your snippet fixed it. :)

    ReplyDelete
  2. Thanks a real lot for this :D

    ReplyDelete
  3. Whoop! No more face desking, thanks so much

    ReplyDelete
  4. I have same problem, but I dont's have will_paginate.rb

    ReplyDelete
    Replies
    1. You have to create the file will_paginate.rb inside of the config/initializers/ folder

      Delete