如何在模型中渲染Jbuidler partials?

时间:2016-06-20 11:06:46

标签: ruby-on-rails ruby-on-rails-4 jbuilder

我试图在这样的模型中渲染jbuilder部分:

class Reminder < ActiveRecord::Base
  ...
  def fcm_format
    Jbuilder.new do |json|
      json.partial! 'api/v1/gigs/summary', gig: remindable
    end
  end
end

但是这给了我以下错误。

  

TypeError:{:gig =&gt;#}不是符号,也不是字符串

有没有办法在模型或装饰器内部渲染部分?

1 个答案:

答案 0 :(得分:5)

Jbuilder实例不响应partial!partial!中包含JbuilderTemplateJbuilderTemplate的构造函数在Jbuilder.new上调用super之前正在查找上下文。

因此解决方案是添加上下文。问题是在JbuilderTemplate内,上下文调用方法render,在模型中我们没有内置的渲染方式。所以我们需要用ActionController::Base对象来隐藏我们的上下文。

class Reminder < ActiveRecord::Base

  # Returns a builder
  def fcm_format
    context = ActionController::Base.new.view_context
    JbuilderTemplate.new(context) do |json|
      json.partial! 'api/v1/gigs/summary', gig: remindable
    end
  end

  # Calls builder.target! to render the json
  def as_json
    fcm_format.target!
  end

  # Calls builder.attributes to return a hash representation of the json
  def as_hash
    fcm_format.attributes!
  end
end
相关问题