как решить этот неопределенный метод `[] 'для nil: NilClass и вызвать результат в файле шаблона - PullRequest
0 голосов
/ 12 октября 2018

У меня есть таблица с таким большим количеством данных (данных транзакций), о которых я хочу сделать полный отчет.Эта таблица имеет Currency, Fee charged, Network Fee Charged, Order Type, Created_at, Updated_at.Например, в этом отчете я хотел бы вычислить сумму fees на основе выбранного диапазона времени и даты, а если дата не выбрана, по умолчанию 30 дней и рассчитать сумму комиссий на основе всех уникальных валют в таблице базы данных.

Достигнув этого, это то, что я сделал , который не работает, но сталкивается с undefined method `[]' for nil:NilClass Error.

module Admin
  module Statistic
    class RevenuesController < BaseController
      def show
        @revenues_grid = ::Statistic::RevenuesGrid.new(params[:statistic_revenues_grid])
        @revenues_reports = []
        Currency.all.each do |currency|
          start_datetime = params.nil? ? 30.days.ago : params[:created_at][0] # This throws the error
          end_datetime = params.nil? ? Time.now : params[:created_at][1] # This throws the error too
          revenues_report_for_currency = get_revenue_report_for_currency(currency, start_datetime, end_datetime)
          @revenues_reports << revenues_report_for_currency
        end
      end

      def get_revenue_report_for_currency(currency, start_datetime, end_datetime)
        total_withdraw_fees_charged = Withdraw.where(:currency => currency.id, :created_at => start_datetime..end_datetime).sum(:fee)
        total_withdraw_network_fees_charged= 0.3 * total_withdraw_fees_charged
        net_income_from_withdraws = total_withdraw_fees_charged - total_withdraw_network_fees_charged

        total_sell_order_fees_charged = Order.where(:type => 'OrderAsk', :bid => currency.id, :created_at => start_datetime..end_datetime).sum(:fee)
        total_buy_order_fees_charged = Order.where(:type => 'OrderBid', :ask => currency.id, :created_at => start_datetime..end_datetime).sum(:fee)
        total_trading_fees = total_sell_order_fees_charged + total_buy_order_fees_charged

        total_fees = net_income_from_withdraws + total_trading_fees

        {
          :total_withdraw_fees_charged =>  total_withdraw_fees_charged,
          :total_withdraw_network_fees_charged =>  total_withdraw_network_fees_charged,
          :net_income_from_withdraws =>  net_income_from_withdraws,
          :total_sell_order_fees_charged =>  total_sell_order_fees_charged,
          :total_buy_order_fees_charged =>  total_buy_order_fees_charged,
          :total_trading_fees =>  total_trading_fees,
          :total_fees => total_fees
        }
      end
    end
  end
end
  1. Как мне решить эту проблему undefined method `[]' for nil:NilClass Error?

1 Ответ

0 голосов
/ 12 октября 2018

Изменить params.nil? в строке start_datetime = params.nil? ? 30.days.ago : params[:created_at][0]

Быть params[:created_at].nil?

Ваш код после изменения будет:

module Admin
  module Statistic
    class RevenuesController < BaseController
      def show
        @revenues_grid = ::Statistic::RevenuesGrid.new(params[:statistic_revenues_grid])
        @revenues_reports = []
        Currency.all.each do |currency|
          start_datetime = params[:created_at].nil? ? 30.days.ago : params[:created_at][0] # This shouldn't throw error
          end_datetime = params[:created_at].nil? ? Time.now : params[:created_at][1] # This shouldn't throw error
          revenues_report_for_currency = get_revenue_report_for_currency(currency, start_datetime, end_datetime)
          @revenues_reports << revenues_report_for_currency
        end
      end

      def get_revenue_report_for_currency(currency, start_datetime, end_datetime)
        total_withdraw_fees_charged = Withdraw.where(:currency => currency.id, :created_at => start_datetime..end_datetime).sum(:fee)
        total_withdraw_network_fees_charged= 0.3 * total_withdraw_fees_charged
        net_income_from_withdraws = total_withdraw_fees_charged - total_withdraw_network_fees_charged

        total_sell_order_fees_charged = Order.where(:type => 'OrderAsk', :bid => currency.id, :created_at => start_datetime..end_datetime).sum(:fee)
        total_buy_order_fees_charged = Order.where(:type => 'OrderBid', :ask => currency.id, :created_at => start_datetime..end_datetime).sum(:fee)
        total_trading_fees = total_sell_order_fees_charged + total_buy_order_fees_charged

        total_fees = net_income_from_withdraws + total_trading_fees

        {
          :total_withdraw_fees_charged =>  total_withdraw_fees_charged,
          :total_withdraw_network_fees_charged =>  total_withdraw_network_fees_charged,
          :net_income_from_withdraws =>  net_income_from_withdraws,
          :total_sell_order_fees_charged =>  total_sell_order_fees_charged,
          :total_buy_order_fees_charged =>  total_buy_order_fees_charged,
          :total_trading_fees =>  total_trading_fees,
          :total_fees => total_fees
        }
      end
    end
  end
end

Лучший подходзаменить

start_datetime = params[:created_at].nil? ? 30.days.ago : params[:created_at][0]
end_datetime = params[:created_at].nil? ? Time.now : params[:created_at][1]

на

start_datetime, end_datetime = params[:created_at].nil? ? [30.days.ago, Time.now] : params[:created_at]
...