Rails没有将Symbol隐式转换为Integer

时间:2014-06-23 16:21:00

标签: ruby-on-rails variables 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

错误:

  

没有将符号隐式转换为整数

1 个答案:

答案 0 :(得分:8)

您已使用

@count设为空String
@count = '';

所以,当您执行@count[:venues_pending]时,Ruby会尝试将符号 :venues_pending转换为整数以访问特定索引字符串@count。 这导致错误为no implicit conversion of Symbol into Integer

当您计划将实例变量@count用作Hash时,您应该将其实例化为哈希而不是空字符串。

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