How do I delegate to a model's to_builder meth

2019-06-17 19:07发布

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.

2条回答
兄弟一词,经得起流年.
2楼-- · 2019-06-17 19:43

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
查看更多
放我归山
3楼-- · 2019-06-17 19:57

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
查看更多
登录 后发表回答