Filtering Custom Controller Actions and Responses in Rails

November 21, 2011 — Leave a comment

I’ve been finishing up an application that has a number of custom controller actions. All except one action – the approved action – require user authorization before retrieving any information from the database.

Specifically, I wanted to authentication the administrator for all actions except the approved action for both JSON and XML responses (but not HTML responses).

Here’s how to do it in Rails 3:

before_filter :authenticate_admin!, :except => [ :approved ]
before_filter (:only => :approved) do |controller|
     controller.send :authenticate_admin! unless controller.request.format.json? || controller.request.format.xml?
end

No Comments

Be the first to start the conversation.

Leave a Reply

*

Text formatting is available via select HTML.

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>