首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在fast_jsonapi中使用Rails路径和URL

在fast_jsonapi中使用Rails路径和URL
EN

Stack Overflow用户
提问于 2020-09-25 18:29:51
回答 2查看 445关注 0票数 0

我想使用rails URL helper,而不是硬编码访问文章的路径。

我签入了documentation,但没有指定任何内容。

article_path助手方法存在(我通过运行rake routes进行了检查)

代码语言:javascript
复制
class V3::ArticlesController < Api::V3::BaseController
  def index
    articles = Article.all
    render json: ::V3::ArticleItemSerializer.new(articles).serialized_json
  end
end

class V3::ArticleItemSerializer
  include FastJsonapi::ObjectSerializer
  attributes :title

  link :working_url do |object|
    "http://article.com/#{object.title}"
  end

  # link :what_i_want_url do |object|
  #   article_path(object)
  # end
end
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-09-25 21:29:50

多亏了max's example,我找到了一个解决方案。

我还将gem更改为jsonapi-serializer

代码语言:javascript
复制
class V3::ArticlesController < Api::V3::BaseController
  def index
    articles = Article.all
    render json: ::V3::ArticleItemSerializer.new(articles, params: { context: self }).serialized_json
  end
end

class V3::ArticleItemSerializer
  include JSONAPI::Serializer
  attributes :title

  link :working_url do |object|
    "http://article.com/#{object.title}"
  end

  link :also_working_url do |object, params|
    params[:context].article_path(object)
  end
end
票数 1
EN

Stack Overflow用户

发布于 2020-09-25 20:19:41

您要做的是将上下文从控制器传递给序列化程序:

代码语言:javascript
复制
module ContextAware
  def initialize(resource, options = {})
    super
    @context = options[:context]
  end
end
代码语言:javascript
复制
class V3::ArticleItemSerializer
  include FastJsonapi::ObjectSerializer
  include ContextAware
  attributes :title

  link :working_url do |object|
    @context.article_path(object)
  end
end
代码语言:javascript
复制
class V3::ArticlesController < Api::V3::BaseController
  def index
    articles = Article.all
    render json: ::V3::ArticleItemSerializer.new(articles, context: self).serialized_json
  end
end

你也应该切换到jsonapi-serializer gem,它目前是在fast_jsonapi被Netflix抛弃时维护的。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64062347

复制
相关文章

相似问题

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