私はRubyonRails 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!'