Home > Mobile >  Rails before_action to allow all actions from a resource
Rails before_action to allow all actions from a resource

Time:11-18

The routes.rb contain:

...
resources :mystuff
...

the application_controller contain:

...
before_action :check_login, except: [:login, :auth]
...

On the login page I have a link_to mystuff_path that never happens.
The problem is that I want to allow all actions in mystuff regardless of login-status.
How do I need to modify the before_action to allow that? (Using Ruby 2.3.1, Rails 5.2.6)

I've tried:

...
before_action :do_stuff
...
def do_stuff
  check_login unless mystuff_path || login_path || auth_path
end
...

which allows mystuff-actions and normal login, but causes ActionController::InvalidAuthenticityToken, which I think is unrelated (to this one) problem to be solved. Also I don't know what else may be clobbered this way, e.g.: validation? ?

CodePudding user response:

Use skip_before_action to skip a callback. For example:

class ApplicationController
  before_action :authenticate_user! # secure by default
end

class PostsController < ApplicationController
  skip_before_action :authenticate_user! # opt out of authentication for this controller
end

It takes the same only, except, if and unless options as before_action which can be used for more fine grained control:

class PostsController < ApplicationController
  skip_before_action :authenticate_user!, only: [:show, :index]
end

class PostsController < ApplicationController
  skip_before_action :authenticate_user!, unless: :some_condition?
end
  • Related