Take the 2-minute tour ×

I am using Ruby on Rails 3 and I am trying to build an ActiveModel this way:

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)

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

    # The following methods are needed to be minimally implemented

    def read_attribute_for_validation(attr)

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

    def Account.lookup_ancestors

    def persisted?

If in my controller I make this

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

I get this error:

undefined method `add' for nil:NilClass

If I make

@new_account = Users::Account.new

the debug of @new_account is

--- !ruby/object:Users::Account 

Where is the error and how can I solve that?

P.S.: I don't want to use validate_presence_of because I need a different validation process, but I think that also that method doesn't work.

If I use the validate! method I get the following error that refers to that

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!'
share|improve this question
Last time I checked namespaced models don't play nice. Is there a particular reason you must have them be namespaced? –  Andrew Marshall Mar 4 '11 at 21:44
Yes, I need namespace in order to organize files in my application. –  user502052 Mar 4 '11 at 21:51
Andrew, what specifically do you think doesn't work with namespaced models? –  Doug R Mar 4 '11 at 22:31
We use namespaced models all the time, no problems here. –  nathanvda Mar 4 '11 at 23:49
add comment

1 Answer

up vote 3 down vote accepted

I think ActiveModel::Validations automatically defines errors for you. You are probably overwriting this when you define

attr_reader :errors
share|improve this answer
Indeed, if you remove the attr_reader and the initialisation of the @errors, it will just work. –  nathanvda Mar 5 '11 at 0:04
add comment

Your Answer


