如何在嵌套变量中访问YAML次级项目?

时间:2011-02-21 14:56:32

标签: ruby-on-rails ruby-on-rails-3

获取错误:

You have a nil object when you didn't expect it!
You might have expected an instance of Array.
The error occurred while evaluating nil.[]

APP_CONFIG正在加载。

account_type = 'sample'
allowed = APP_CONFIG['account']["#{account_type}"]['highlight']

错误指向'允许'变量行。

我目前尝试的方法是:

  def self.allow_highlight?(account)
    account_type = Account.find(account).active_pack # returning a string - OK
    logger.debug account_type.class # checked on console - OK
    allowed = APP_CONFIG['account']["#{account_type}"]['highlight'] # Error line
    if total_account_highlight > allowed
        false
    else
        true
    end
  end

希望你理解。 有任何疑问,请问我。

谢谢!

2 个答案:

答案 0 :(得分:1)

我首先要确保在初始化程序中设置了APP_CONFIG。

其次,如果APP_CONFIG或account_type为nil会出现此错误,您实际上是在代码之前的那一行之前设置了account_type,还是从某处提供并且实际上不包含值?如果account_type为nil,为空或包含YAML文件中未提供的值,则会引发错误。因此,您应该验证这两个变量的内容。

另外,如果您刚刚在初始化程序中创建了APP_CONFIG,请确保重新启动Rails,因为它只会在服务器初始化时更新

答案 1 :(得分:0)

account_type应该是字符串:

 allowed = APP_CONFIG['account']["#{account_type.to_s}"]['highlight']

 allowed = APP_CONFIG['account']["#{account_type.class}"]['highlight']