简体   繁体   English

您如何在 Rails 6 上使用/ERB Ruby 迭代一系列数字?

[英]How do you iterate over a range of numbers with each do with/ ERB Ruby on Rails 6?

I am attempting to iterate over a range of years for a method that passes on unique years to a where clause in ruby on rails.我正在尝试迭代多年的方法,该方法将独特的年份传递到轨道上 ruby 中的 where 子句。 For some odd reason, it does not fire off when I attempt to pass those numbers down to the method chain.出于某种奇怪的原因,当我尝试将这些数字传递给方法链时,它不会触发。 For starters, I am working on a reporting feature that tracks charts by years in between a range.对于初学者来说,我正在开发一个报告功能,该功能可以在一个范围内按年跟踪图表。 For example: Search starts at 2020 and ends at 2024. All years from 2020 to 2024 will show a report for each year compiled together.例如:搜索从 2020 年开始,到 2024 年结束。从 2020 年到 2024 年的所有年份都会显示汇总在一起的每一年的报告。 Right now, I only get one year and I should be getting 2020, 2021 and 2024 on one response..How can I print out a range of years by integer and pass them through the each block to the corresponding method?现在,我只有一年,我应该在一个响应中得到 2020、2021 和 2024 年。如何通过 integer 打印出一系列年份并将它们通过每个块传递给相应的方法?

Example code below:下面的示例代码:

params {start_year: "2019", end_year: "2020"}

params[:start_year], params[:end_year]

<% [@start_year.to_i+1...@end_year.to_i].each do |facility_year| %>
   <% @facility.chart_records.where('extract(year from record_date) =?', facility_year).limit(11).each do |chart_record| %>
<tr>
<td><%= chart_record.record_date.strftime("%Y") %></td>
<td>Month: Jan</td>
<td><%= ChartRecord.where(facility_id: @facility.id).where('extract(month from record_date) =?', 1).where('extract(year from record_date) =?', facility_year).sum(:fit_jeans_count)</td>
</tr>
<% end %>

I just want to get one unique year from the start_year+1 count up until the end_year count and then display one record for each year in the range..我只想从 start_year+1 计数到 end_year 计数获得一个唯一的年份,然后显示该范围内每一年的一条记录..

For ranges use parentheses (@start_year.to_i+1...@end_year.to_i) not brackets.对于范围,使用括号(@start_year.to_i+1...@end_year.to_i)而不是括号。 With brackets, you create an array with only one item that contains a range.使用括号,您可以创建一个数组,其中只有一个包含范围的项目。 With parentheses, you'll get a range right away.使用括号,您将立即获得一个范围。

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

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