【问题标题】:creating singular resources in jsonapi-resources在 jsonapi-resources 中创建单一资源
【发布时间】:2016-04-25 17:54:40
【问题描述】:

在我的情况下,使用 jsonapi-resources gem(和 Rails 4),我正在尝试创建一个单一(或单例)资源(不提供标准显示、更新和删除请求的 url 上的 id)对于当前(登录)用户的个人资料,所以我可以执行“GET /profiles”而不是“GET /profiles/:id”。

我已将单数路由添加到 config/routes.rb 文件中:

jsonapi_resource:配置文件

根据文件https://github.com/cerebris/jsonapi-resources#jsonapi_resource

那么如何修改资源(ProfileResource)以将 id 映射到 current_user(通过上下文)?

现有的演示应用程序没有演示使用单一资源,并且似乎没有任何文档(明确)解决这个问题。

【问题讨论】:

    标签: ruby-on-rails singleton jsonapi-resources


    【解决方案1】:

    在您的配置文件资源中,如果键是“我”,您可以覆盖 self.find_by_key 方法以通过存储在上下文中的用户进行实例化。 对于当前用户,您可以点击/profiles/me

    def self.find_by_key(key, options = {})
      new(options[:context][:current_user], options[:context]) if key == 'me'
    end
    

    【讨论】:

      【解决方案2】:

      这行得通! (谢谢)

      对我来说关键是

      config/routes.rb

      jsonapi_resource :profile
      

      在 app/resources/profile_resource.rb 中

      def self.find_by_key(key, options = {})
        model = options[:context][:current_user]
        fail JSONAPI::Exceptions::RecordNotFound.new(key) if model.nil?
        new(model, options[:context])
      end
      

      然后点击(GET,PUT,POST,DELETE) '/profile' 工作正常。

      【讨论】:

        猜你喜欢
        • 2016-09-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多