简体   繁体   English

如何在 Rails 上的 Ruby 中的 Model 中通过迭代格式化对象数组

[英]How do I format an array of objects by iteration in Model in Ruby on Rails

I want to format an array of objects to send a substitution data in a Model.我想格式化一个对象数组以在 Model 中发送替换数据。 I would like to format that by iterating through a data called, "bags" and it's also an array of objects.我想通过迭代一个名为“bags”的数据来格式化它,它也是一个对象数组。 For example,例如,

bags = [{id: 1, name: "name1", product_id: 1}, {id: 2, name: "name2", product_id: 2"}]

The data "bags" has a relationship with "product" model so each bag has one product.数据“bags”与“product”model 有关系,因此每个bags 都有一个产品。 I know I can get the "product" data by doing:我知道我可以通过以下方式获取“产品”数据:

bags.map{|bag| bag.package}

However, I'm confused on how to use the result and re-format it as an array of object, since the result comes as an array.但是,我对如何使用结果并将其重新格式化为 object 数组感到困惑,因为结果以数组形式出现。

I want to iterate through "bags" and use its relationship to get the "product" data to create an array of objects like this:我想遍历“包”并使用它的关系来获取“产品”数据来创建一个对象数组,如下所示:

bag: 
   [
    {bag_name: "name1", product_name: "product1"}, 
    {bag_name: "name2", product_name: "product2"}
   ]

Please let me know if you need further information.如果您需要更多信息,请告诉我。

from what I'm understanding, you are trying to map bags into an array of object for each bag.据我了解,您正在尝试将 map 包放入每个包的 object 数组中。 Here is how I'd probably do with the information you've given:以下是我可能会如何处理您提供的信息:

bags.map do |bag|
  {bag_name: bag[:name], product_name: bag.package}
end

In this function, bag[:name] return the name properties of each bag, whereas bag.package returns the product "data" you mentioned.在这个 function 中, bag[:name]返回每个包的名称属性,而bag.package返回您提到的产品“数据”。 It map through the bags array and output an array of objects using map method.它使用 map 通过bags数组和 output 对象数组使用map方法。

Feel free to give it a try and update here if there's any further errors/problems.如果有任何进一步的错误/问题,请随时尝试并在此处更新。

Cheers:)干杯:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM