我在Rails中使用Gem(AutoStripAttributes)时遇到问题

时间:2015-03-24 15:08:24

标签: ruby-on-rails gem

这很奇怪,之前我使用过很多宝石,并在整个项目中使用各种宝石。

我正在尝试使用名为AutoStripAttributes(https://github.com/holli/auto_strip_attributes)的宝石

我已将其包含在我的gemfile(gem "auto_strip_attributes", "~> 2.0")中,并运行了bundle install

Installing auto_strip_attributes 2.0.6

一切都很好。

然而,当我去使用它时......

class User < ActiveRecord::Base
  has_many :...
  has_many :...
  has_many :...
  has_many :...

  before_save { self.email = email.downcase }

  validates :name,  presence: true, uniqueness: { case_sensitive: false }, length: { maximum: 25 }
  VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
  validates :email, presence: true, format: { with: VALID_EMAIL_REGEX },
                  uniqueness: { case_sensitive: false }, length: { minimum: 6, maximum: 255 }

  has_secure_password validations: true
  validates :password, length: { minimum: 6 }, allow_nil: true 

  auto_strip_attributes :name

我得到以下输出......

NoMethodError (undefined method `auto_strip_attributes' for #<Class:0x007fe929502f7>):
  app/models/user.rb:21:in `<class:User>'
  app/models/user.rb:1:in `<top (required)>'

为什么这不起作用?

编辑:

rails c
AutoStripAttributes

2.1.3 :079 > AutoStripAttributes
NameError: uninitialized constant AutoStripAttributes
from (irb):79
from /Users/a/.rvm/gems/ruby-2.1.3/gems/railties-4.1.0/lib/rails/commands/console.rb:90:in `start'
from /Users/a/.rvm/gems/ruby-2.1.3/gems/railties-4.1.0/lib/rails/commands/console.rb:9:in `start'
from /Users/a/.rvm/gems/ruby-2.1.3/gems/railties-4.1.0/lib/rails/commands/commands_tasks.rb:69:in `console'
from /Users/a/.rvm/gems/ruby-2.1.3/gems/railties-4.1.0/lib/rails/commands/commands_tasks.rb:40:in `run_command!'
from /Users/a/.rvm/gems/ruby-2.1.3/gems/railties-4.1.0/lib/rails/commands.rb:17:in `<top (required)>'
from /Users/a/Developer/rails/fffapi/bin/rails:8:in `<top (required)>'
from /Users/a/.rvm/rubies/ruby-2.1.3/lib/ruby/2.1.0/rubygems/core_ext/kernel_require.rb:55:in `require'
from /Users/a/.rvm/rubies/ruby-2.1.3/lib/ruby/2.1.0/rubygems/core_ext/kernel_require.rb:55:in `require'
from -e:1:in `<main>'

和...

a$ bundle show | grep auto_strip_attributes
  * auto_strip_attributes (2.0.6)

1 个答案:

答案 0 :(得分:0)

我已安装在这里进行测试,一切正常。

在您的Gemfile中,您是否强制将此gem加载到特定组?

例:

gem "auto_strip_attributes", "~> 2.0", group: :production

或者:

group :development, :test do
  gem "auto_strip_attributes", "~> 2.0"
end

在控制台(rails c),您致电AutoStripAttributes时返回了什么?是这样的吗?

$ rails c

Loading development environment (Rails 4.2.0)
2.2.0 :001 > AutoStripAttributes
 => AutoStripAttributes

或者您有NameError: uninitialized constant AutoStripAttributes错误?

另外,bundle show | grep auto_strip_attributes的结果是什么?