Rails 4和Jbuilder,如何为模型集合调用to_builder方法



我在Location模型上定义了一个to_builder方法。方法如下:

class Location < ActiveRecord::Base
  def to_builder
    Jbuilder.new do |json|
      json.(self, :id, :latitude, :longitude, :name, :description)
    end
  end
end

如果我从数据库中选择一个Location,我可以将其转换为JSON,如下所示:

Location.first.to_builder.target!

这很管用。如何对一组Location模型执行同样的操作?例如,如果我通过一个关系(Area has_many :locations)从数据库中获得多个。

locations = Area.first.locations

有没有一种简单的方法可以用Jbuilder将locations转换为json?我目前的解决方案是定义一个助手方法,为我将模型或集合转换为json。例如:

def json_for(object)
  if object.is_a? ActiveRecord::Relation
    a = object.map do |o|
      o.to_builder.target!
    end
    "[#{a.join(',')}]".html_safe
  else
    object.to_builder.target!.html_safe
  end
end

然后我会打电话给json_for locations。但这感觉不是正确的处理方式

更新

我还没有找到一个很好的解决方案。目前,我正在使用我编写的助手来呈现JSON视图的内容。以下是助手的样子:

def json_for(view, locals_hash = {})
  render(template: view, formats: [:json], locals: locals_hash).html_safe
end

然后,我在视图中使用这样的助手,传入视图中使用的任何变量:

<%= json_for 'locations/index', { locations: @locations } %>

我也有一个帮助部分:

def json_for_partial(partial, locals_hash = {})
  render(partial: partial, formats: [:json], locals: locals_hash).html_safe
end

总之,我根本没有使用to_builder方法。相反,我创建了实际的jbuilder视图文件,然后使用助手在应用程序中任何需要的地方渲染他们生成的JSON。

您可以将集合渲染为一个数组,该数组利用to_builder覆盖,如下所示:

Jbuilder.new do |json| 
  json.array! locations.map do |l|
    l.to_builder.attributes!
  end
end.target!

https://github.com/rails/jbuilder/issues/139

https://github.com/rails/jbuilder/issues/75