Ruby NoMethodError:[]:Array的未定义方法`messages'

Ste*_*ies 2 ruby ruby-on-rails rails-activerecord

由于谷歌没有帮助我解决这个问题,我想我会分享给其他遇到这个问题的人:

在尝试保存模型时,我明白了

NoMethodError: undefined method `messages' for []:Array
0: /.../active_record/autosave_association.rb:491:in `_ensure_no_duplicate_errors'
1: /.../active_support/callbacks.rb:413:in `block in make_lambda'
2: /.../active_support/callbacks.rb:246:in `block in halting'
3: /.../active_support/callbacks.rb:511:in `block in invoke_after'
4: /.../active_support/callbacks.rb:511:in `each'
5: /.../active_support/callbacks.rb:511:in `invoke_after'
6: /.../active_support/callbacks.rb:132:in `run_callbacks'
7: /.../active_support/callbacks.rb:825:in `_run_validation_callbacks'
8: /.../active_model/validations/callbacks.rb:110:in `run_validations!'
9: /.../active_model/validations.rb:335:in `valid?'
Run Code Online (Sandbox Code Playgroud)

示例型号:

class Foo < ActiveRecord::Base

  def do_stuff
    @errors = []
    @errors << 'Bad stuff' if self.bar > 4
    @errors
  end

end
Run Code Online (Sandbox Code Playgroud)

示例代码:

foo = Foo.first
foo.do_stuff
foo.save # or foo.valid?, etc.
Run Code Online (Sandbox Code Playgroud)

Ste*_*ies 6

原因

此错误消息的原因是Foo该类创建实例级@errors变量.

ActiveRecord跟踪模型errors变量中的数据库错误.当您尝试验证模型时,它会检查此变量中的错误消息.

解决方案

更改@errors为其他名称(例如@foo_errors).