Search code examples
ruby-on-railsrubyauthenticationbefore-filter

Rails: How to use a before_filter to protect multiple methods


So, I have this code in a controller:

before_filter :require_login, :only => :new, :edit, :destroy

My controller has these methods: index, new, edit, create, update, show, destroy. What I want to do is to protect with login_required (:require_login in the code) the methods: new, edit, destroy, but the above code doesn't work, I can protect one method if i have, for example:

before_filter :require_login, :only => :new

But I want to protect the three of them, How can I do it?


Solution

  • You're missing square brackets around the only option's value:

     before_filter :require_login, :only => [:new, :edit, :destroy]
    

    It's not working because the Ruby interpreter doesn't know where the options for only start and the arguments for before_filter continue. This is case where you need to be explicit about the container.