Rails 没有将符号隐式转换为整数 [英] Rails no implicit conversion of Symbol into Integer

查看:54
本文介绍了Rails 没有将符号隐式转换为整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to create a private method that does some counting based on some database data as follows.

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

错误:

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

no implicit conversion of Symbol into Integer

推荐答案

You have set @count as a empty String with

You have set @count as an empty String with

@count = '';

因此,当您执行 @count[:venues_pending] 时,Ruby 会尝试转换 Symbol :venues_pendingInteger 以访问字符串 @count 的特定索引.这导致错误为没有将符号隐式转换为整数

so when you do @count[:venues_pending], Ruby tries to convert the Symbol :venues_pending to an Integer to access a particular index of the String @count. This is resulting in the error as no implicit conversion of Symbol into Integer

由于您计划使用实例变量 @count 作为 Hash,您应该将其实例化为 Hash 而不是空字符串.

As you are planning to use the instance variable @count as a Hash, you should instantiate it as a Hash rather than an empty String.

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

这篇关于Rails 没有将符号隐式转换为整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆