开发者

Trouble building an ActiveModel in Ruby on Rails 3 using namespaces

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)
    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

If in my controller I make this

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

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 
id: 
name: 
surname: 
updated_at: 

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!'


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

attr_reader :errors
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜