我想使用rails URL helper,而不是硬编码访问文章的路径。
我签入了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发布于 2020-09-25 21:29:50
多亏了max's example,我找到了一个解决方案。
我还将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发布于 2020-09-25 20:19:41
您要做的是将上下文从控制器传递给序列化程序:
module ContextAware
def initialize(resource, options = {})
super
@context = options[:context]
end
endclass V3::ArticleItemSerializer
include FastJsonapi::ObjectSerializer
include ContextAware
attributes :title
link :working_url do |object|
@context.article_path(object)
end
endclass 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抛弃时维护的。
https://stackoverflow.com/questions/64062347
复制相似问题