on Rails的3在Ruby中建立一個加載ActiveModel,我試圖建立一個加載ActiveModel this way:故障使用on Rails的3我使用Ruby命名空間
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:
哪裏錯誤,我怎麼能解決?
P.S:我不想用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!'
我上次檢查命名空間模型不好玩。是否有一個特定的原因,你必須讓它們被命名空間? – 2011-03-04 21:44:15
是的,我需要名稱空間才能組織我的應用程序中的文件。 – user502052 2011-03-04 21:51:16
安德魯,你認爲什麼具體名稱空間模型不起作用? – 2011-03-04 22:31:54