0

我有两个数组,我正在使用 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
4

1 回答 1

1

正确的处理方法是设置两个表系统并分组、连接和选择聚合。

# rails g model site name lat:decimal lon:decimal
class Site < ApplicationRecord
  # This is a truely ridiculous name
  # @see https://en.wikipedia.org/wiki/Weathers_(band)
  has_many :weathers 

  def self.with_aggregates(from: 7.days.ago, to: Time.current)
    w = Weather.arel_table
    left_joins(:weathers)
      .select(
        :id,
        w[:rain].sum.as('total_rain'),
        w[:temperature].average.as('average_temperature'),
        w[:temperature].maximum.as('high_temperature'),
        w[:temperature].minimim.as('low_temperature')
      )
      .group(:id)
      .where(weathers: { timestamp: from..to })
  end
end
# for the love of god use the correct terms 
# Observation or Forecast instead of abusing the english language
class Weather < ApplicationRecord
  belongs_to :site # Use `site_id` instead of `site_no`.
end

这将让您简单地显示它而无需压缩任何东西,因为您实际上做得正确并让数据库进行数字运算。

<% Site.with_aggregates.each do |site| %>
 <%= site.id %> | <%= site.average_temperature %> | <%= site.total_rain %>
<% end %>
于 2020-11-02T22:24:54.730 回答