ruby-on-railsbefore-filter

Error using private or protected methods in subclasses of ApplicationController


I have a filter shared between some controllers, which is primarily declared as private in ApplicationController. This method sets find and pagination conditions for controllers.

class ApplicationController < ActionController::Base
  ...
  protected # or private
    # Define parametros de busca
    def set_find_opts(klass)
      @filter = params[:f].to_i || nil
      
      @order = klass.set_order params[:o]
      
      @opts = { :page => params[:page] }
      @opts[:order] = @order if @order
    end
    ...
end

class Admin::UsersController < AdminController
  ...
  before_filter(:only => :index) {|c| c.set_find_opts User }
  ...
end

I'm getting this error:

  1) Error:
test_should_get_index(Admin::UsersControllerTest):
NoMethodError: protected method `set_find_opts' called for #<Admin::UsersControl
ler:0x848f3ac>
    app/controllers/admin/users_controller.rb:4
    functional/admin/users_controller_test.rb:9:in `test_should_get_index'

Why it happens?


Solution

  • You can't send private/protected messages with an explicit receiver (object.protected_method) like you are doing in your block. You can try c.send(:set_find_opts, User) or c.instance_eval { set_find_opts(User) }.