【问题标题】:Active Model Serializer : link_to is not working活动模型序列化器:link_to 不工作
【发布时间】:2014-08-06 21:00:13
【问题描述】:

我实际上是在我的应用程序中实现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"

关于如何解决此问题的想法?

【问题讨论】:

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


    【解决方案1】:

    尝试这样做:

      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
    

    【讨论】:

    • 很棒的伙伴,你成就了我的一天。谢谢
    猜你喜欢
    • 2018-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多