2011-03-04 83 views
1

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

我上次檢查命名空間模型不好玩。是否有一個特定的原因,你必須讓它們被命名空間? – 2011-03-04 21:44:15

+0

是的,我需要名稱空間才能組織我的應用程序中的文件。 – user502052 2011-03-04 21:51:16

+0

安德魯,你認爲什麼具體名稱空間模型不起作用? – 2011-03-04 22:31:54

回答

3

我想::加載ActiveModel驗證自動爲您定義的錯誤。你可能覆蓋這個,當你定義

attr_reader :errors 
+1

事實上,如果你刪除'attr_reader'和'@ errors'的初始化,它就會起作用。 – nathanvda 2011-03-05 00:04:56