Ruby on rails Rails 4和Jbuilder,如何为模型集合调用_builder方法

Ruby on rails Rails 4和Jbuilder,如何为模型集合调用_builder方法,ruby-on-rails,jbuilder,Ruby On Rails,Jbuilder,我已经在我的位置模型上定义了一个to_builder方法。方法如下: class Location < ActiveRecord::Base def to_builder Jbuilder.new do |json| json.(self, :id, :latitude, :longitude, :name, :description) end end end 这很有效。如何对位置模型集合执行相同的操作?例如,如果我通过一个关系(一个区域有许多:位置)

我已经在我的
位置
模型上定义了一个
to_builder
方法。方法如下:

class Location < ActiveRecord::Base
  def to_builder
    Jbuilder.new do |json|
      json.(self, :id, :latitude, :longitude, :name, :description)
    end
  end
end
这很有效。如何对
位置
模型集合执行相同的操作?例如,如果我通过一个关系(一个
区域
有许多:位置
)从数据库中获取多个

有没有一种简单的方法可以使用Jbuilder将
位置
转换为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\u查找位置。但这似乎不是正确的处理方式

更新

我还没有找到解决这个问题的好办法。目前,我正在使用我编写的助手来呈现JSON视图的内容。以下是帮助器的外观:

def json_for(view, locals_hash = {})
  render(template: view, formats: [:json], locals: locals_hash).html_safe
end
然后,我在视图中像这样使用帮助器,传入视图中使用的任何变量:

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

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

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

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


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

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


您有没有找到解决方案?我目前正在尝试完成同样的事情。@请检查我的更新。这不是一个真正的“解决方案”,但这是我目前正在做的事情,以获得我所需要的。也许这对你也有用。你有没有找到解决办法?我目前正在尝试完成同样的事情。@请检查我的更新。这不是一个真正的“解决方案”,但这是我目前正在做的事情,以获得我所需要的。也许这对你也有用。