Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I delegate to a model's to_builder method from a JBuilder view?

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.

like image 958
Chris Aitchison Avatar asked Mar 28 '13 02:03

Chris Aitchison


2 Answers

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
like image 124
yasuoza Avatar answered Sep 17 '22 20:09

yasuoza


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
like image 27
Nathan Avatar answered Sep 18 '22 20:09

Nathan