0

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

我检查了文档,但没有指定任何内容。

article_path辅助方法存在(我通过运行检查rake routes

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
4

2 回答 2

1

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

我还将宝石更改为jsonapi-serializer

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
于 2020-09-25T13:29:49.880 回答
1

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

module ContextAware
  def initialize(resource, options = {})
    super
    @context = options[:context]
  end
end
class V3::ArticleItemSerializer
  include FastJsonapi::ObjectSerializer
  include ContextAware
  attributes :title

  link :working_url do |object|
    @context.article_path(object)
  end
end
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 放弃。

于 2020-09-25T12:19:41.050 回答