得到"未定义的方法`[]'为零:NilClass"在创建记录时

时间:2015-01-26 14:16:35

标签: ruby-on-rails-4

我正在将一个旧的Rails 3应用程序移植到Rails 4.0.15并且一切似乎都很顺利,只要每当我尝试创建一个记录时(即使在Rails控制台中)我都会收到上述错误(未定义的方法&#39) ; []'对于nil:NilClass)。

我在这里过分简化了一些事情,但我所做的是创建一个新应用(rails new xxxx),然后从旧版本复制app/db/树。我使用了相同的数据库。 routes.rb和Gemfile是手动调整的。

其中一个模型是联系方式:

class Contact < ActiveRecord::Base
  attr_accessible :name, :email, :phone, :address
end

rails console中,当我输入Contact.create时,我得到以下信息:

Loading development environment (Rails 4.1.5)
irb(main):001:0> Contact.create
NoMethodError: undefined method `[]' for nil:NilClass
    from /usr/share/gems/gems/activerecord-4.1.5/lib/active_record/attribute_methods/read.rb:113:in `block in read_attribute'
    from /usr/share/gems/gems/activerecord-4.1.5/lib/active_record/attribute_methods/read.rb:111:in `fetch'
    from /usr/share/gems/gems/activerecord-4.1.5/lib/active_record/attribute_methods/read.rb:111:in `read_attribute'
    from /usr/share/gems/gems/activerecord-4.1.5/lib/active_record/attribute_methods/primary_key.rb:19:in `id'
    from /usr/share/gems/gems/activerecord-4.1.5/lib/active_record/transactions.rb:344:in `remember_transaction_record_state'
    from /usr/share/gems/gems/activerecord-4.1.5/lib/active_record/transactions.rb:282:in `rollback_active_record_state!'
    from /usr/share/gems/gems/activerecord-4.1.5/lib/active_record/transactions.rb:267:in `save'
    from /home/wucolin/.gem/ruby/gems/protected_attributes-1.0.3/lib/active_record/mass_assignment_security/persistence.rb:46:in `create'
    from (irb):1
    from /usr/share/gems/gems/railties-4.1.5/lib/rails/commands/console.rb:90:in `start'
    from /usr/share/gems/gems/railties-4.1.5/lib/rails/commands/console.rb:9:in `start'
    from /usr/share/gems/gems/railties-4.1.5/lib/rails/commands/commands_tasks.rb:69:in `console'
    from /usr/share/gems/gems/railties-4.1.5/lib/rails/commands/commands_tasks.rb:40:in `run_command!'
    from /usr/share/gems/gems/railties-4.1.5/lib/rails/commands.rb:17:in `<top (required)>'
    from bin/rails:8:in `require'
    from bin/rails:8:in `<main>'

最佳案例场景:我希望有人会看到这一点然后去#34;是的,这很容易解决。你要做的只是......&#34;

但是,如果有人能指出我正确的方向或从哪里开始,我会很高兴。

谢谢大家的时间。

1 个答案:

答案 0 :(得分:1)

&#34; attr_accessible&#34;功能在Rails 4中消失了。我建议不要使用gem,有很多问题报告。

而不是推动&#34;受保护&#34;进入Rails 4,安装strong_parameters gem并将Rails 3中的强参数功能反向移植。

这绝对是一种更合适的方法。