【问题标题】:Rails 4 and Jbuilder, how to call to_builder method for a collection of modelsRails 4和Jbuilder,如何为模型集合调用to_builder方法
【发布时间】:2016-01-28 20:19:44
【问题描述】:

我在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 模型的集合做同样的事情?例如,如果我通过关系(Areahas_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。

【问题讨论】:

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

标签: ruby-on-rails jbuilder


【解决方案1】:

您可以将集合呈现为利用您的 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

【讨论】:

    猜你喜欢
    • 2013-03-18
    • 2015-12-17
    • 1970-01-01
    • 2014-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-19
    相关资源
    最近更新 更多