将 Rails 路径和 URL 助手与 fast_jsonapi 一起使用

Using Rails Path and URL Helpers with fast_jsonapi

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

我检查了 documentation 但没有指定任何内容。

存在 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

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

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 放弃。

感谢 ,我找到了解决方案。

我也把gem改成了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