Ruby/Rails:为什么 render json: {hello: 'world'} 命中我的数据库?
Ruby/Rails: Why is render json: {hello: 'world'} hitting my database?
我有一个动作:
def test
_process_action_callbacks.map { |c| pp c.filter }
render json: {hello: 'world'}
end
出于某种原因调用我的应用程序控制器中定义的 current_user 函数。
起初我认为这是调用我的 current_user 函数的前操作(因此 _process_action_callbacks)。但是在剥离了我之前的所有操作之后,电话仍然存在。只有两个之前的动作是 rails:
的一部分
:clean_temp_files
:set_turbolinks_location_header_from_session
我使用 caller 查看我的方法是从哪里调用的。这是堆栈跟踪(和方法声明):
def current_user
pp caller
# get the current user from the db.
end
如您所见,current_user 函数正在被序列化 class 中的 serialization_scope 方法调用。如何防止它调用我的 current_user 函数?
您的标签表明您正在使用 active-model-serializers
。默认情况下 current_user
是范围。要自定义在应用程序控制器中定义的范围,您可以执行
class ApplicationController < ActionController::Base
serialization_scope :current_admin
end
以上示例会将范围从 current_user
(默认值)更改为 current_admin
。
在你的情况下,你可能只想在你的控制器中设置范围(我假设它被称为 SomeController
;))你可以写
class SomeController < ApplicationController
serialization_scope nil
def test
render json: {hello: 'world'}
end
end
查看完整文档:https://github.com/rails-api/active_model_serializers/tree/0-9-stable#customizing-scope
我有一个动作:
def test
_process_action_callbacks.map { |c| pp c.filter }
render json: {hello: 'world'}
end
出于某种原因调用我的应用程序控制器中定义的 current_user 函数。
起初我认为这是调用我的 current_user 函数的前操作(因此 _process_action_callbacks)。但是在剥离了我之前的所有操作之后,电话仍然存在。只有两个之前的动作是 rails:
的一部分:clean_temp_files
:set_turbolinks_location_header_from_session
我使用 caller 查看我的方法是从哪里调用的。这是堆栈跟踪(和方法声明):
def current_user
pp caller
# get the current user from the db.
end
如您所见,current_user 函数正在被序列化 class 中的 serialization_scope 方法调用。如何防止它调用我的 current_user 函数?
您的标签表明您正在使用 active-model-serializers
。默认情况下 current_user
是范围。要自定义在应用程序控制器中定义的范围,您可以执行
class ApplicationController < ActionController::Base
serialization_scope :current_admin
end
以上示例会将范围从 current_user
(默认值)更改为 current_admin
。
在你的情况下,你可能只想在你的控制器中设置范围(我假设它被称为 SomeController
;))你可以写
class SomeController < ApplicationController
serialization_scope nil
def test
render json: {hello: 'world'}
end
end
查看完整文档:https://github.com/rails-api/active_model_serializers/tree/0-9-stable#customizing-scope