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

流过昼夜 提交于 2019-12-23 08:55:09

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!