【问题标题】:Using Rails Path and URL Helpers with fast_jsonapi通过 fast_jsonapi 使用 Rails 路径和 URL 助手
【发布时间】:2021-01-11 16:26:18
【问题描述】:

我想使用 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

【问题讨论】:

    标签: ruby-on-rails ruby serialization fastjsonapi


    【解决方案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 弃用。

    【讨论】:

    • 另外请注意,您应该始终明确地嵌套模块和类以避免令人惊讶的不断查找。 github.com/rubocop-hq/ruby-style-guide#namespace-definition
    • 它不适用于 ContextAware 模块,可能是因为我在 app/serializers 文件夹中创建了它?我发布了另一个解决方案
    • 我很高兴它成功了。不确定到底出了什么问题,因为我没有实际测试它,而是把它写成一个概念性的答案。
    【解决方案2】:

    感谢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
    

    【讨论】:

      猜你喜欢
      • 2013-09-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-11
      • 1970-01-01
      相关资源
      最近更新 更多