简体   繁体   English

遍历数据,以数组形式存储在Ruby on Rails中

[英]Loop through data, store as array in Ruby on Rails

This is a very beginner question, but I've searched and can't find anything. 这是一个非常初学者的问题,但是我已经搜索了,找不到任何东西。 I'm attempting to loop through an object, then store the information in an array (or object?) so that I can spit out a string of the items. 我试图遍历对象,然后将信息存储在数组(或对象?)中,以便可以吐出一串物品。

<% @da = [] %>
<% @report.data_items.each do |di| %>
      <% if di.status == "Complete" %>
        <% @da += di.url_metric.da %> #not sure how to append to the end of the array
      <% end %>
<% end %>

Help? 救命? Should I use an array or object? 我应该使用数组还是对象?

Seems that you're doing this in ERB template for some reason. 似乎出于某种原因您正在ERB模板中执行此操作。 Don't. 别。 Keep templates clear and simple. 保持模板简洁明了。 Do this kind of calculations in controller. 在控制器中进行这种计算。

Here's a better version: 这是一个更好的版本:

@da = @report.data_items.select {|di| di.status == 'Complete'}.
                         map{|di| di.url_metric.da }
@da = @report.data_items.collect{|di| di.url_metric.da if di.status == "Complete"}.compact

Here's shorted varian of what you're trying to accomplish: 这是您要完成的任务的简写:

@da = @report.data_items.select do |item|
  item.status == "Complete"
end.map { |item| item.url_metric.da }.join(", ")

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

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