Search code examples
ruby-on-railsruby

Rails 7 - How to run a before action with inline code only for an action


In Rails 7.1 with Ruby 3.2.2, what's the correct syntax to run a before_action filter with inline code only for a specific action?

I have tried everything suggested in Before action with inline method, but I always get an error.

before_action only: :destroy, { authorize!(with: AllowAllPolicy) }
before_action only: [:destroy], { authorize!(with: AllowAllPolicy) }
before_action { authorize!(with: AllowAllPolicy) }, only: :destroy
before_action { authorize!(with: AllowAllPolicy) }, only: [:destroy]
before_action { authorize!(with: AllowAllPolicy), only: :destroy }
before_action { authorize!(with: AllowAllPolicy), only: [:destroy] }
before_action(only: :destroy, { authorize!(with: AllowAllPolicy) })
before_action(only: [:destroy], { authorize!(with: AllowAllPolicy) })

Solution

  • You were so close. Your first option without the comma is what you're after, with a small tweak to resolve the precedence issue, so either:

    before_action(only: :destroy) { authorize!(with: AllowAllPolicy) }
    
    ## or
    
    before_action only: :destroy do
      authorize!(with: AllowAllPolicy)
    end