Search code examples
ruby-on-rails-3before-filter

make a before_filter with current_user


I would like to make a before_filter on a controller with the method :current_user
And it works...
But I have an admin boolean in the user's attributes and I would like that only the users who have this boolean at "true" use the controller.
How can I do that ?

Thank you for your answer


Solution

  • You can use any method that returns a boolean value as a before_filter in rails. So in your case, just make a method like

    def is_admin?
      return (current_user && current_user.admin?)
    end
    

    and then call before_filter is_admin? at the top of your controller with the actions you want to filter.

    Note that short-circuit evaluation of && ensures that admin? is not called on current_user if it is nil.