【问题标题】:Merging one attribute for all records into array using Jbuilder使用Jbuilder将所有记录的一个属性合并到数组中
【发布时间】:2016-10-07 21:07:52
【问题描述】:

我有一个产品集合,每个都有多个标签。我想组合所有标签的名称,以便我拥有所有标签名称的数组。

期望的输出:

{
    "title": "Product1", 
    "tags": ["name1", "name2", "name3"]
}

我目前的 jbuilder 正在给我:

{Products: [{
    "title": "Product1",
    "tags":[
        {"tag1":
           {"name": "name1"}
         },
        {"tag2": 
           {"name": "name2"}
         },
        {"tag3":
           {"name": "name3"}
         }
      ]
}]}

我目前的 jbuilder。

json.array! @products do |product|
    json.title product.title
    json.tags product.tags do |tag|
        json.name tag.name
    end
end

感谢您的帮助!

【问题讨论】:

  • 你试过没有json.tags product.tags 块的json.tags product.tags 吗?
  • 我仍然得到嵌套标签对象。从本质上讲,我需要一个标签名称数组等于 json.tags。
  • 好的,可以试试json.tags product.tags.map(&:name)

标签: ruby-on-rails jbuilder


【解决方案1】:

只需从每个标签中提取标签名称!

json.array! @products do |product|
    json.title product.title
    json.tags product.tags.map(&:name)
end

如果标签是一个关系,您可以改用pluck 来提高效率

json.array! @products do |product|
    json.title product.title
    json.tags product.tags.pluck(:name)
end

【讨论】:

  • 非常感谢! Pluck 就是我要找的东西!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-09-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-18
  • 2014-05-26
相关资源
最近更新 更多