ruby-on-railsrubyserializationfastjsonapi

Using Rails Path and URL Helpers with fast_jsonapi


I would like to use the rails URL helper instead of hard coding the path to access the article.

I checked into the documentation but nothing is specified.

The article_path helper method exists (I checked by running 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

Solution

  • I found a solution thanks to max's example.

    I also changed the gem to 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