首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用jsonapi-resources时,上下文始终为空

使用jsonapi-resources时,上下文始终为空
EN

Stack Overflow用户
提问于 2015-10-24 23:59:46
回答 3查看 775关注 0票数 4

结合使用jsonapi-resources gem的0.6.0版本和Doorkeeper,我在我的资源的context对象中看到当前用户时遇到了问题。

我基本上是在遵循the docs,但是我所做的任何尝试都不会使我在ApplicationController中设置的context在资源的fetchable_fields方法中可见。我确实确认了我的ApplicationController中确实设置了context

这是我所拥有的

ApplicationController

代码语言:javascript
复制
class ApplicationController < JSONAPI::ResourceController
  protect_from_forgery with: :null_session

  def context
    {current_user: current_user}
  end
end

控制器

代码语言:javascript
复制
class Api::ItemsController < ApplicationController
  prepend_before_action :doorkeeper_authorize!
end

资源

代码语言:javascript
复制
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
EN

回答 3

Stack Overflow用户

发布于 2016-03-11 06:53:02

好的,使用jsonapi资源之上创建的jsonapi-utils gem,你可以这样写:

ApplicationController:

代码语言:javascript
复制
class ApplicationController < JSONAPI::ResourceController
  include JSONAPI::Utils
  protect_from_forgery with: :null_session
end

ItemsController:

代码语言:javascript
复制
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

无需定义上下文:-)

我希望它能对你有所帮助。干杯!

票数 0
EN

Stack Overflow用户

发布于 2020-02-11 19:13:45

以您为例,以下是我的解决方案

资源

代码语言:javascript
复制
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
票数 0
EN

Stack Overflow用户

发布于 2016-08-09 08:02:03

您不需要在ApplicationController中使用context方法。上下文实际上是通过框架在Resource类中提供的。在您的资源中,您可以访问:

代码语言:javascript
复制
@context[:current_user]
票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/33320189

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档