Active Model Serializer:link_to不起作用

时间:2014-06-16 23:47:16

标签: ruby-on-rails active-model-serializers render-to-string

我实际上已将Active Model Serializers实施到我的应用程序中。到目前为止,一切都按预期工作,但现在我还需要发送(JSON)一个html部分以及我的数据。这是我做的:

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

问题是此代码引发undefined method 'host' for nil:NilClass。正如你在上面的代码中看到的那样,我试过include Rails.application.routes.url_helpers但是没有运气,它仍然没有用。

我试图重新启动Rails应用程序,但也没有运气。在我看来,问题来自我在我的部分中使用的link_to方法:

%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"

如何解决此问题的想法?

1 个答案:

答案 0 :(得分:4)

尝试这样做:

  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