Using Rails Path and URL Helpers with fast_jsonapi

773 views Asked by At

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
2

There are 2 answers

0
Guillaume On BEST ANSWER

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
3
max On

What you want to do is pass in the context to your serializer from your controller:

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

You should also switch to the jsonapi-serializer gem which is currently maintained as fast_jsonapi was abandoned by Netflix.