如何从JBuilder视图委托给模型的to_builder方法? [英] How do I delegate to a model's to_builder method from a JBuilder view?
本文介绍了如何从JBuilder视图委托给模型的to_builder方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有一个Person类和一个Gang类
Let's say I have a Person class and a Gang class
class Person
belongs_to :gang
attr_accessible :name, :secret
def to_builder
Jbuilder.new do |app|
person.id id
person.name name
end
end
end
class Gang
has_many :people
attr_accessible :name
end
如何从视图中使用此to_builder方法?
How do I use this to_builder method from a view?
例如
#app/views/gang/show.json.jbuilder (@gang set by the controller)
json.gang do |json|
json.name @gang.name
json.gang_members(@gang.people) do |person|
#how do I delegate to the person.to_builder here?
end
end
请记住,我永远都不想只使用默认的Person.as_json,因为我不想在Person上呈现secret
属性.
Mind you, I do not ever just want to use the default Person.as_json, because I do not want to render the secret
attribute on Person.
我尝试过的大多数方法最终都渲染了Person.as_json的等效内容,而不是Person.to_builder.
Most of the things I have tried have ended up rendering the equivalent of Person.as_json, not Person.to_builder.
推荐答案
您可以使用Jbuilder#attributes!
.我的意思是
You can use Jbuilder#attributes!
. I mean
json.gang do |json|
json.name @gang.name
json.gang_members @gang.people.map { |person| person.to_builder.attributes! }
end
这篇关于如何从JBuilder视图委托给模型的to_builder方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文