使用命名空间在Ruby on Rails 3上构建ActiveModel时出现问题

时间:2021-12-12 23:18:03

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

我正在使用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

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

@new_account的调试是

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

P.S。:我不想使用validate_presence_of,因为我需要一个不同的验证过程,但我认为该方法也不起作用。


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

1 个解决方案

#1


3  

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

我认为ActiveModel :: Validations会自动为您定义错误。您可能在定义时覆盖了这个

attr_reader :errors

#1


3  

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

我认为ActiveModel :: Validations会自动为您定义错误。您可能在定义时覆盖了这个

attr_reader :errors