Active_model_serializers: Best way url_helpers to work in json adapter (not json_api)?

Created on 12 Aug 2016  路  4Comments  路  Source: rails-api/active_model_serializers

Hi!
i'm not using json_api adapter, so link method is not working for me.
Can you please advise good way to resolve problem with undefined url or path?

class ResourceSerializer < ApplicationSerializer
  attribute :embed_code

  def embed_code
    "<iframe src=\"#{embed_resource_url(object)}\"></iframe>"
  end
end
Question 0.10.x

Most helpful comment

Yes, this is fastest approach, but this requires :host in default_url_options and I don't like it, because url helper method in view context returns correct url, based on request I think. I don't like this idea for json_api also.
Another solution (which works without specifying host):

class ApplicationController < ActionController::Base
  serialization_scope :view_context
end

class ResourceSerializer < ApplicationSerializer
  attribute :embed_code

  def embed_code
    "<iframe src=\"#{view_context.embed_resource_url(object)}\"></iframe>"
  end
end

All 4 comments

Try include Rails.application.routes.url_helpers

Yes, this is fastest approach, but this requires :host in default_url_options and I don't like it, because url helper method in view context returns correct url, based on request I think. I don't like this idea for json_api also.
Another solution (which works without specifying host):

class ApplicationController < ActionController::Base
  serialization_scope :view_context
end

class ResourceSerializer < ApplicationSerializer
  attribute :embed_code

  def embed_code
    "<iframe src=\"#{view_context.embed_resource_url(object)}\"></iframe>"
  end
end

@attenzione you'll need to either write a custom adapter or one of the above options. I'm going to close this issue as resolved since it is squarely in userland, but please report back here what you end up doing for others who are interested.

@bf4 currently i'm using solution, what I've provided before. This way I have access to all helpers without including them in each/some serializers, more flexible. I will report if I find some other solution

Was this page helpful?
0 / 5 - 0 ratings

Related issues

adamcrown picture adamcrown  路  4Comments

steverob picture steverob  路  4Comments

djsegal picture djsegal  路  5Comments

yjukaku picture yjukaku  路  5Comments

JohnMerlino2 picture JohnMerlino2  路  3Comments