因此,我不确定是否有更好的方法可以解决此问题,但是我打算在Rails应用程序中实现一些基本的访问控制。我想做的是检查current_user
,查看他们属于哪个公司,然后从那里确定他们是否有权访问他们要导航的内容。他们的公司has_many
与公司有关联,因此根据current_user
进入公司并从那里出发是我的逻辑。
但是,我要解决的一个问题是:我无法从current_user
访问ApplicationController.
变量,这只是没有定义。
根据此处Access devise current_user variable in rails controller的一些建议,我可以只添加before_action :authenticate_user!
,但这已经在我的ApplicationController
中。此外,尝试调用user_signed_in?
也不起作用,因为这是未定义的方法。
我不明白为什么我可以用authenticate_user!
调用before_action
方法,但是之后却无法访问变量。
这是我的应用程序控制器。
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
before_action :configure_permitted_parameters, if: :devise_controller?
before_action :authenticate_user!
protected
def configure_permitted_parameters
attributes = [:first_name, :last_name, :email]
devise_parameter_sanitizer.permit(:sign_up, keys: attributes)
devise_parameter_sanitizer.permit(:account_update, keys: attributes)
end
def after_sign_out_path_for(resource_or_scope)
flash[:notice] = "You have successfully signed out."
new_user_session_path
end
end
关于为什么即使调用了current_user
方法后仍无法访问authenticate_user!
方法的任何建议?
我想一种替代方法是在每个单独的控制器中添加单独的功能,以检查用户是否可以访问该控制器中的对象,但这似乎可能成为一场噩梦。
谢谢您的建议。
编辑
在这里我叫current_user
和user_signed_in?
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
before_action :configure_permitted_parameters, if: :devise_controller?
before_action :authenticate_user!
binding.pry
protected
def configure_permitted_parameters
attributes = [:first_name, :last_name, :email]
devise_parameter_sanitizer.permit(:sign_up, keys: attributes)
devise_parameter_sanitizer.permit(:account_update, keys: attributes)
end
def after_sign_out_path_for(resource_or_scope)
flash[:notice] = "You have successfully signed out."
new_user_session_path
end
end
在放置binding.pry的位置,尝试在应用程序暂停后从Rails控制台手动调用它,但是它提到它不可用。