NameError:未初始化的常量User :: SCREEN_NAME_RANGE

时间:2011-08-28 12:07:09

标签: ruby-on-rails

所以根据Railsspace的教程,我想使用控制台来理解Active Records。所以我做了我应该做的事情,这就是我得到的结果。

有谁知道问题出在哪里?

   $ rails console

输出

Loading development environment (Rails 3.0.10)
ruby-1.9.2-p290 :001 > user = User.new(:screen_name => "me",
ruby-1.9.2-p290 :002 >     :email => "",
ruby-1.9.2-p290 :003 >     :password => "a",)
NameError: uninitialized constant User::SCREEN_NAME_RANGE
    from /Users/dennisbuizert/Sites/gpoff/app/models/user.rb:3:in `<class:User>'
    from /Users/dennisbuizert/Sites/gpoff/app/models/user.rb:1:in `<top (required)>'
    from (irb):1
    from /Users/dennisbuizert/.rvm/gems/ruby-1.9.2-p290/gems/railties-3.0.10/lib/rails/commands/console.rb:44:in `start'
    from /Users/dennisbuizert/.rvm/gems/ruby-1.9.2-p290/gems/railties-3.0.10/lib/rails/commands/console.rb:8:in `start'
    from /Users/dennisbuizert/.rvm/gems/ruby-1.9.2-p290/gems/railties-3.0.10/lib/rails/commands.rb:23:in `<top (required)>'
    from script/rails:6:in `require'
    from script/rails:6:in `<main>'

用户模型

    class User < ActiveRecord::Base
  validates_uniqueness_of :screen_name, :email
  validates_length_of     :screen_name, :within => SCREEN_NAME_RANGE
  validates_length_of     :password,    :within => PASSWORD_RANGE
  validates_length_of     :email,       :maximum => EMAIL_MAX_LENGTH
  validates_presence_of   :email

  # Max & Min length for all fields
  SCREEN_NAME_MIN_LENGTH  = 3
  SCREEN_NAME_MAX_LENGTH  = 20
  PASSWORD_MIN_LENGTH     = 8
  PASSWORD_MAX_LENGTH     = 26
  EMAIL_MAX_LENGTH        = 50
  SCREEN_NAME_RANGE = SCREEN_NAME_MIN_LENGHT..SCREEN_NAME_MAX_LENGTH
  PASSWORD_RANGE = PASSWORD_MIN_LENGHT..PASSWORD_MAX_LENGTH

end

我使用的是SQLite3而不是MySQL,因为我无法弄清楚如何用mysql替换SQLite3以及如何使其工作。

3 个答案:

答案 0 :(得分:4)

我看到错误的来源。您必须在验证之前声明常量。加载类时,您在验证中引用的常量尚未声明,因此错误。

您的代码应如下所示:

class User < ActiveRecord::Base

  # Max & Min length for all fields
  SCREEN_NAME_MIN_LENGTH  = 3
  SCREEN_NAME_MAX_LENGTH  = 20
  PASSWORD_MIN_LENGTH     = 8
  PASSWORD_MAX_LENGTH     = 26
  EMAIL_MAX_LENGTH        = 50
  SCREEN_NAME_RANGE = SCREEN_NAME_MIN_LENGHT..SCREEN_NAME_MAX_LENGTH
  PASSWORD_RANGE = PASSWORD_MIN_LENGHT..PASSWORD_MAX_LENGTH

  validates_uniqueness_of :screen_name, :email
  validates_length_of     :screen_name, :within => SCREEN_NAME_RANGE
  validates_length_of     :password,    :within => PASSWORD_RANGE
  validates_length_of     :email,       :maximum => EMAIL_MAX_LENGTH
  validates_presence_of   :email

end

答案 1 :(得分:0)

要让sqlite正常运行,请确保gem sqlite3中有Gemfile行,运行bundle install,并使config/database.yml中的部分看起来像这样:< / p>

development:
  adapter: sqlite3
  database: db/development.sqlite3
  pool: 5
  timeout: 5000

至于SCREEN_NAME_RANGE错误,我无法在不看到您的代码的情况下判断它的来源(假设上述配置更改无法解决)。如果您完全确定您的文件与教程中显示的文件完全相同,我会联系作者,因为它是非免费的文档集。

您可能想查看http://guides.rubyonrails.org/。他们有很大的警告说他们是不完整的,但在大多数情况下,他们的写得非常好(并且是由公众积极参与的社区成员),而且是免费的。

答案 2 :(得分:0)

在自动测试运行时编辑模型文件时会出现此问题

所以只需停止自动测试然后再次启动它(如果你想)