0

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
Guillaume
  • 1,437
  • 2
  • 15
  • 17

2 Answers2

1

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.

max
  • 96,212
  • 14
  • 104
  • 165
  • Also note that you should always explicitly nest modules and classes to avoid suprising constant lookups. https://github.com/rubocop-hq/ruby-style-guide#namespace-definition – max Sep 25 '20 at 12:21
  • It didn't work with the ContextAware module, maybe because I created it into the app/serializers folder? I posted another solution – Guillaume Sep 25 '20 at 13:29
  • I'm glad it worked out. Not sure exactly what's going wrong as I didn't actually test it and wrote it more as a conceptual answer. – max Sep 25 '20 at 13:33
1

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
Guillaume
  • 1,437
  • 2
  • 15
  • 17