我有两个数组,我正在使用 zip 方法将它们连接在一起形成一个循环。当 zip 方法中不存在记录时,我遇到了一个问题,它会抛出数据的顺序。
例如:
我的观点
<% @temperature.zip(@rain).each do |temp, rain| %>
<%= temp.site_no %> | <%= temp.temperature %> | <%= rain.present? ? rain.total_rain : '0' %>
<% end %>
应以以下方式显示数据:
Site no | Temp | Rain
1 | 20 | 10
2 | 22 | 0
3 | 18 | 3
但是因为@rain zip 方法中不存在站点二,所以它会将第二行数据放在最后。我有两个变量,因为我每天早上 8 点访问总降雨量。
控制器
@temperature = Weather.select('DISTINCT ON(site_no) site_no, temperature, lat, long, timestamp').group(:site_no, :temperature, :lat, :long, : timestamp).order(: site_no).where('timestamp > ?', 7.days.ago)
@rain = Weather.select('site_no, SUM(rain) as total_rain').where('timestamp > ?', 7.days.ago).where('timestamp::time = ?', "08:00").group(:site_no)
因此,站点 2 在选择的任何日期的上午 8 点都没有下雨,因此在 @rain 变量中不存在。我试图通过条件匹配 by site_no,但仍然没有运气。
架构
create_table "weathers", force: :cascade do |t|
t.integer "site_no"
t.decimal "temperature"
t.decimal "rain"
t.datetime "timestamp"
t.decimal "lat"
t.decimal "long"
end