【问题标题】:Context is always nil using jsonapi-resources使用 jsonapi-resources 上下文始终为零
【发布时间】:2016-01-24 01:02:52
【问题描述】:

将 jsonapi-resources gem 的 0.6.0 版本与 Doorkeeper 结合使用,我无法在资源的 context 对象中看到当前用户。

我基本上是在关注the docs,但是我没有尝试使我在ApplicationController 中设置的context 在资源的fetchable_fields 方法中可见。我确实确认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

【问题讨论】:

  • 你有没有得到答案,我遇到了类似的事情?
  • 我没有@withakay。我最终不需要这样做,但我们可能应该在 github 中打开一个问题,因为它似乎不太可能在这里得到解决。
  • 我猜:doorkeeper_authorize! 有一个叫current_user 的方法?你确定它工作正常吗?

标签: ruby-on-rails json-api jsonapi-resources


【解决方案1】:

以你为例,这是我的解决方案

资源

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

【讨论】:

    【解决方案2】:

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

    @context[:current_user]
    

    【讨论】:

    • 什么?那么如果不是控制器,current_user 是从哪里来的呢?
    • Doorkeeper 不提供有关资源的上下文
    【解决方案3】:

    好吧,使用 jsonapi-utils gem——它是在 jsonapi-resources 之上创建的——你会写这样的东西:

    应用控制器:

    class ApplicationController < JSONAPI::ResourceController
      include JSONAPI::Utils
      protect_from_forgery with: :null_session
    end
    

    ItemsController:

    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
    

    无需定义上下文:-)

    希望对你有帮助。干杯!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-02
      • 2012-01-16
      • 2020-01-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多