53

I'm having trouble getting before filters to work in a Rails app I have recently upgraded from 1.9(?) to 2.3.11. To try and debug it, I have put a before_filter in a controller:

before_filter :false_filter

and the following in application_controller.rb:

def false_filter
  puts "false filter running"
  false
end

I then call the method from either cucumber/webrat or a browser, and while the filter is getting called (I can see the puts outputting the message), the filter chain isn't getting terminated.

I'm wondering if there's some boilerplate code that hasn't been generated. Can anyone suggest where to look?

1
  • 9
    You are probably confused with active record before_xxx method which are not saving the record when returning false Jun 15, 2011 at 7:13

1 Answer 1

99

Nothing pays any attention to a before-filter's return value. If you want to stop processing, you have to render something from your filter or redirect to somewhere else, from the fine guide:

If a before filter renders or redirects, the action will not run. If there are additional filters scheduled to run after that filter they are also cancelled.

The same text appears in the 5.2.0 guide.

This behavior does make sense, if the filter chain doesn't complete (i.e. stops filtering part way through) then you'd end up calling controller methods with things not set up the way they were expecting them to be and that would just cause pain, suffering, and confusion and that wouldn't be at all friendly or fun.

4
  • 7
    The examples I was looking at do a redirect and then return false, and I latched on to the false part, which turned out to be exactly so. It all makes perfect sense - thanks. Jun 15, 2011 at 20:28
  • 10
    @Henry: Don't feel bad, I find a lot of the Rails and Ruby documentation to be a little sparse on details like this. Jun 15, 2011 at 20:46
  • @muistooshort Need some help. I was going through Design patterns , and most of them using Interface which is not the subject of Ruby. So, I'm not able to understand them. Any tips how to learn those? I'm not able to code them in Ruby. Line by line translations I don't think will be a better option. Please advise me. Feb 12, 2015 at 6:35
  • 2
    This is extremely helpful. The quoted text is very explicit and exactly what I needed to see. Aug 18, 2015 at 20:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.