Rails没有将Symbol隐式转换为Integer

Har*_*M V 1 variables ruby-on-rails ruby-on-rails-4

我正在尝试创建一个私有方法,根据一些数据库数据进行一些计数,如下所示.

class ApplicationController < ActionController::Base
  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
  protect_from_forgery with: :exception

    before_action :moderation_count

    private

    def moderation_count
      @count = '';
      @count[:venues_pending] = Venue.where(:is_approved => 0).count.to_i
      @count[:venues_rejected] = Venue.where(:is_approved => 2).count.to_i
      @count[:venue_photos_pending] = VenuePhoto.where(:is_approved => 0).count.to_i
      @count[:venue_photos_rejected] = VenuePhoto.where(:is_approved => 2).count.to_i
      @count[:venue_reviews_pending] = VenueReview.where(:is_approved => 0).count.to_i
      @count[:venue_reviews_rejected] = VenueReview.where(:is_approved => 2).count.to_i
    end
end
Run Code Online (Sandbox Code Playgroud)

错误:

没有将Symbol隐式转换为Integer

Kir*_*rat 8

您已设置@count为空String

@count = '';
Run Code Online (Sandbox Code Playgroud)

所以,当你这样做@count[:venues_pending],Ruby尝试将转换符号 :venues_pending 到一个整数访问字符串的特定指标@count.这导致错误no implicit conversion of Symbol into Integer

当您计划将实例变量@count用作a时Hash,您应该将其实例化为Hash而不是空String.

使用@count = {};@count = Hash.new;