在 jsonapi-resources 中创建单一资源
creating singular resources in jsonapi-resources
使用 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(通过上下文)?
现有的演示应用程序没有演示如何使用单一资源,而且似乎没有任何文档(明确地)解决这个问题。
在您的配置文件资源中,如果键是 'me',您可以覆盖 self.find_by_key
方法以通过存储在上下文中的用户实例化。
对于当前用户,您可以点击 /profiles/me
。
def self.find_by_key(key, options = {})
new(options[:context][:current_user], options[:context]) if key == 'me'
end
行得通! (感谢)
对我来说关键是
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' 工作正常。
使用 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(通过上下文)?
现有的演示应用程序没有演示如何使用单一资源,而且似乎没有任何文档(明确地)解决这个问题。
在您的配置文件资源中,如果键是 'me',您可以覆盖 self.find_by_key
方法以通过存储在上下文中的用户实例化。
对于当前用户,您可以点击 /profiles/me
。
def self.find_by_key(key, options = {})
new(options[:context][:current_user], options[:context]) if key == 'me'
end
行得通! (感谢)
对我来说关键是
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' 工作正常。