结合使用jsonapi-resources gem的0.6.0版本和Doorkeeper,我在我的资源的context对象中看到当前用户时遇到了问题。
我基本上是在遵循the docs,但是我所做的任何尝试都不会使我在ApplicationController中设置的context在资源的fetchable_fields方法中可见。我确实确认了我的ApplicationController中确实设置了context。
这是我所拥有的
ApplicationController
class ApplicationController < JSONAPI::ResourceController
protect_from_forgery with: :null_session
def context
{current_user: current_user}
end
end控制器
class Api::ItemsController < ApplicationController
prepend_before_action :doorkeeper_authorize!
end资源
class Api::ItemResource < JSONAPI::Resource
# attributes
def fetchable_fields
# context is always nil here
if (context[:current_user].guest)
super - [:field_i_want_private]
else
super
end
end
end发布于 2016-03-11 06:53:02
好的,使用jsonapi资源之上创建的jsonapi-utils gem,你可以这样写:
ApplicationController:
class ApplicationController < JSONAPI::ResourceController
include JSONAPI::Utils
protect_from_forgery with: :null_session
endItemsController:
class API::ItemsController < ApplicationController
prepend_before_action :doorkeeper_authorize!
before_action :load_user
def index
jsonapi_render json: @user.items
end
private
def load_user
@user = User.find(params[:id])
end
end无需定义上下文:-)
我希望它能对你有所帮助。干杯!
发布于 2020-02-11 19:13:45
以您为例,以下是我的解决方案
资源
class Api::ItemResource < JSONAPI::Resource
# attributes
def fetchable_fields
# context is always nil here
if (context[:current_user].guest)
super - [:field_i_want_private]
else
super
end
end
# upgrade
def self.create(context)
# You can use association here but not with association table
# only works when `id` is inside the table of the resource
ItemResource.new(Item.new, context)
end
before_save do
# Context is now available with `self.context`
self.context[:current_user]
end
end发布于 2016-08-09 08:02:03
您不需要在ApplicationController中使用context方法。上下文实际上是通过框架在Resource类中提供的。在您的资源中,您可以访问:
@context[:current_user]https://stackoverflow.com/questions/33320189
复制相似问题