问题
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
How do I use this to_builder method from a view?
For example
#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
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.
Most of the things I have tried have ended up rendering the equivalent of Person.as_json, not Person.to_builder.
回答1:
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
回答2:
Use Jbuilder#merge!
to merge in the attributes from the person builder.
json.gang do
json.name @gang.name
json.gang_members(@gang.people) do |person|
json.merge! person.to_builder.attributes!
end
end
来源:https://stackoverflow.com/questions/15673160/how-do-i-delegate-to-a-models-to-builder-method-from-a-jbuilder-view