pic*_*ter 0 ruby-on-rails jbuilder ruby-on-rails-4
我试图在这样的模型中渲染一个jbuilder部分:
class Reminder < ActiveRecord::Base
...
def fcm_format
Jbuilder.new do |json|
json.partial! 'api/v1/gigs/summary', gig: remindable
end
end
end
Run Code Online (Sandbox Code Playgroud)
但这给了我以下错误。
TypeError:{:gig =>#}既不是符号也不是字符串
有没有办法渲染模型或装饰器的局部内部?
一个Jbuilder实例不响应partial!。partial!包含在中JbuilderTemplate。JbuilderTemplate的构造函数在调用super on之前正在寻找上下文Jbuilder.new。
因此解决方案是添加上下文。问题在于,在中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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
338 次 |
| 最近记录: |