为什么在.each的每次迭代中都显示相同的数据

时间:2015-12-11 14:11:55

标签: ruby ruby-on-rails-4 sequel

我已经尝试根据@wifis(基于mac_id)生成数据但是当前数据与以下代码相同 -

控制器:

class DashboardsController < ApplicationController
  before_action :authenticate_user!
  def show
    @wifis = Wifi.where(user_id: current_user.id)
    pdaily_number_of_logins_data = []
    phourly_total_traffic_data = []
    pper_user_monthly_traffic_data = []
    @wifis.each do |wifi|
      daily_number_of_logins_data = Radacct.fetch("SELECT gd_day(acctstarttime, 'UTC') AS date, COUNT(*) AS count FROM radacct WHERE (`calledstationid` = ?) AND (`acctstarttime` >= ?) GROUP BY date", wifi.mac_id, 1.month.ago)
      pdaily_number_of_logins_data += daily_number_of_logins_data.to_a if daily_number_of_logins_data.to_a
      @daily_number_of_logins = pdaily_number_of_logins_data.collect{|i| [i[:date],i[:count]]}
      hourly_total_traffic_data = Radacct.fetch("SELECT gd_hour_of_day(acctstarttime, 'UTC') AS hour_of_day, ROUND(((SUM(acctinputoctets)+SUM(acctoutputoctets))/1049000)) AS totaltraffic FROM radacct WHERE (`calledstationid` = ?) AND (`acctstarttime` >= ?) GROUP BY hour_of_day", wifi.mac_id, 1.day.ago)
      phourly_total_traffic_data += hourly_total_traffic_data.to_a if hourly_total_traffic_data.to_a
      @hourly_total_traffic = phourly_total_traffic_data.collect{|i| [i[:hour_of_day],i[:totaltraffic]]}
      per_user_monthly_traffic_data = Radacct.fetch("SELECT username, ROUND(((SUM(acctinputoctets)+SUM(acctoutputoctets))/1049000)) AS `traffic` FROM `radacct` WHERE (`calledstationid` = ?) AND (`acctstarttime` >= ?) GROUP BY username", wifi.mac_id, 1.month.ago)
      pper_user_monthly_traffic_data += per_user_monthly_traffic_data.to_a if per_user_monthly_traffic_data.to_a
      @per_user_monthly_traffic = pper_user_monthly_traffic_data.collect{|i| [i[:username],i[:traffic]]}
    end
  end
end

和查看:

% @wifis.each do |wifi| %>
  <h1><%= wifi.mac_id %></h1>
  <%= line_chart @daily_number_of_logins, { discrete: true, library: {hAxis: {title: "Date"}, vAxis: {title: "Number of Logins (daily)"}}} %>
  <%= column_chart @hourly_total_traffic, {library: {hAxis: {title: "Hour"}, vAxis: {title: "Traffic in Megabytes (hourly)"}}} %>
  <%= pie_chart @per_user_monthly_traffic, discrete: true %>
<% end %>

我已根据这个答案尝试了上述问题,但我遇到的问题是@wifi对象在控制器和视图中使用:Loop within Loop in Rails Controller

1 个答案:

答案 0 :(得分:0)

问题是控制器操作中的循环运行并在每次迭代时覆盖实例变量。所以只剩下最后一次迭代。如果您想为每个wifi保存数据,则需要另一种数据结构,而不是普通的ivars。也许哈希是关键的哈希。

@counters = {}
@wifis.each do |wifi|
  @counters[wifi] ||= {}
  @counters[wifi][:daily_number_of_logins] = ...

然后在视图中

  <% @wifis.each do |wifi| %>
    <%= line_chart @counters[wifi][:daily_number_of_logins] %>
  <% end %>