application_controller.rb中的代码未被其他控制器继承



我读到ApplicationController的使用是将其视为所有其他控制器的父级。任何进入其中的代码也将在所有其他控制器中运行。因为我使用我的应用程序更像API,所以我将skip_before_action :verify_authenticity_token放在我的application_controller.rb文件中,这样我就可以从外部域使用我的程序。由于某些原因,它不起作用(它仍然会阻塞连接(。相反,我必须将这行代码放入每个控制器中才能使其工作(现在跳过了身份验证/外部域可以使用应用程序(。

虽然把代码放在每个控制器中并不麻烦,但我对ApplicationController的正确用法感到困惑,并怀疑自己是否做错了什么。

非常感谢您的帮助!:(

这是ApplicationController的代码

class ApplicationController < ActionController::Base
skip_before_action :verify_authenticity_token
end

这是另一个控制器的代码(注意:skip_before_action :verify_authenticity_token应该被ApplicationController删除/继承,如上所述。

class SessionsController < ActionController::Base
include CurrentUserConcern
skip_before_action :verify_authenticity_token
def create
user = User.find_by(email: params["user"]["email"]).try(:authenticate, params["user"]["password"])
if User
session[:user_id] = user.id
render json: {
status: :created,
logged_in: true,
user: user
}
else
render json: {
status: 401
}
end
end
def logged_in
if @current_user
render json: {
logged_in: true,
user: @current_user
}
else
render json: {
logged_in: false
}
end
end
def logout
reset_session
render json: {
status: 200,
logged_out: true
}
end
end

您的SessionsController继承自ActionController::Base,将sessionController的类定义从class SessionsController < ActionController::Base更改为class SessionsController < ApplicationController。它不会自动从applicationController继承。您必须在要从其继承的控制器中指定它。

最新更新