如何在模型中渲染 Jbuilder 部分?
How to render Jbuidler partials inside a model?
我正在尝试在这样的模型中渲染 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=>#} is not a symbol nor a string
有没有办法在模型或装饰器内部渲染部分内容?
一个 Jbuilder
实例没有响应 partial!
。 partial!
包含在 JbuilderTemplate
中。 JbuilderTemplate
的构造函数在 Jbuilder.new
.
上调用 super 之前正在寻找上下文
所以解决办法就是加个context。问题是在 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
我正在尝试在这样的模型中渲染 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=>#} is not a symbol nor a string
有没有办法在模型或装饰器内部渲染部分内容?
一个 Jbuilder
实例没有响应 partial!
。 partial!
包含在 JbuilderTemplate
中。 JbuilderTemplate
的构造函数在 Jbuilder.new
.
所以解决办法就是加个context。问题是在 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