1

我正在使用 Ruby on Rails 3,我正在尝试以这种方式构建 ActiveModel :

module Users # I use a namespace
  class Account
    extend ActiveModel::Naming
    extend ActiveModel::Translation
    include ActiveModel::Validations

    attr_accessor :name
    attr_reader :errors

    def initialize
      @errors = ActiveModel::Errors.new(self)
    end

    def validate!
      errors.add(:name, "can not be nil") if name == nil
    end

    # The following methods are needed to be minimally implemented

    def read_attribute_for_validation(attr)
      send(attr)
    end

    def Account.human_attribute_name(attr, options = {})
      attr
    end

    def Account.lookup_ancestors
      [self]
    end


    def persisted?
      false
    end
end

如果在我的控制器中我做这个

def create
  @account = Users::Account.new
  @account.errors.add( :name, "can not be blank" )
  ...
end

我收到此错误:

undefined method `add' for nil:NilClass

如果我做

@new_account = Users::Account.new

的调试@new_account

--- !ruby/object:Users::Account 
id: 
name: 
surname: 
updated_at: 

错误在哪里,我该如何解决?


PS:我不想使用validate_presence_of,因为我需要不同的验证过程,但我认为该方法也行不通。


如果我使用该validate!方法,我会收到以下错误,即

NoMethodError in Users/accountsController#create

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

Application trace
pp/models/users/account.rb:16:in `validate!'
4

1 回答 1

3

我认为 ActiveModel::Validations 会自动为您定义错误。当您定义时,您可能会覆盖它

attr_reader :errors
于 2011-03-04T22:31:13.793 回答