Active Model Serializers : undefined method `url_for' for nil:NilClass

半城伤御伤魂 提交于 2019-12-05 20:27:19

Ok, I finally found a work around. The problem really came from my edit 2 point in the above post.

To fix it, since I was already using the rails_config gem (https://github.com/railsjedi/rails_config) in my app, I've used it in order to be able to render my partials directly from my serializer without breaking the Rails magic autoloading.

First, I'm setting up the context as a config (Settings) :

# application_controller
class ApplicationController < ActionController::Base
  before_filter :set_context_for_serializer

  def set_context_for_serializer
    Settings.context = self
  end
end

Then, within my serializer, all I need to do is :

class ApplicationSerializer < ActiveModel::Serializer
  def render_partial_to_json(options = {})
    partial = options[:partial] || nil
    locals  = options[:locals] || nil

    Settings.context.render_to_string(
      partial: partial,
      layout: false,
      formats: :html,
      locals: locals
    )
  end
end

class ActivitySerializer < ApplicationSerializer
  attributes :id, :kind, :data, :created_at, :html

  def html
    render_partial_to_json(
      partial: 'activities/post',
      locals: { activity: object }
    )
  end
end

And that's it, now it works perfectly. If you guys have some other way (more Rails like) to do it, I'll be curious to know about it.

Thanks

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!