Search code examples
ruby-on-railsactive-model-serializersrender-to-string

Active Model Serializer : link_to is not working


I'm actually implementing the Active Model Serializers into my application. Everything worked as expected so far, but now I need to also send (JSON) a html partial along with my datas. Here is what I did :

class ActivitySerializer < ActiveModel::Serializer
  include Rails.application.routes.url_helpers

  attributes :id, :kind, :data, :created_at, :html

  has_many :comments

  def html
    controller = ApplicationController.new
    controller.render_to_string(
      partial: 'activities/post',
      layout: false,
      formats: :html,
      locals: { activity: object }
    )
  end
end

The problem is that this code raise an undefined method 'host' for nil:NilClass. As you can see in the code above, I've tried to include Rails.application.routes.url_helpers but no luck, it still not working.

I've tried to restart the Rails app but no luck either. It's seems to me that the problem comes from the link_to method that I'm using in my partial :

%article.comment-item.m-t
  = link_to profile_url(activity.user), class: "pull-left thumb-sm avatar" do
    = display_picture_for activity.user, resizing_by: "36x36"

Ideas on how to work around this issue?


Solution

  • Try do like this:

      def html
        context = Rails.configuration.paths['app/views']
        view = ActionView::Base.new(context)
        view.class.include Rails.application.routes.url_helpers
        view.render :partial => 'activities/post',
                    :locals =>  {activity: object}
      end