2011-06-13 32 views
3

在Rails 3中,您只需包含ActiveRecord模塊以便爲任何非數據庫支持的模型添加驗證。我想創建一個表單模型(例如ContactForm模型)幷包含ActiveRecord賦值。但是你不能簡單地在Rails 2.3.11中包含ActiveRecord模塊。有什麼辦法可以像Rails 2.3.11一樣完成Rails 3的行爲?Rails 2.3.11爲表單創建模型並使用ActiveRecord驗證

回答

2

如果您只是想使用虛擬類作爲多種模型的驗證代理,以下可能會有所幫助(對於2.3.x,3.xx,您可以按照前面的說明使用ActiveModel):

class Registration 
    attr_accessor :profile, :other_ar_model, :unencrypted_pass, :unencrypted_pass_confirmation, :new_email 
    attr_accessor :errors 

    def initialize(*args) 
    # Create an Errors object, which is required by validations and to use some view methods. 
    @errors = ActiveRecord::Errors.new(self) 
    end 

    def save 
    profile.save 
    other_ar_model.save 
    end 
    def save! 
    profile.save! 
    other_ar_model.save! 
    end 

    def new_record? 
    false 
    end 

    def update_attribute 
    end 
    include ActiveRecord::Validations 
    validates_format_of :new_email, :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i 
    validates_presence_of :unencrypted_pass 
    validates_confirmation_of :unencrypted_pass 
end 

這種方式可以包括驗證子模塊,它會抱怨,如果你嘗試定義它們之前將其列入savesave!方法不可用。可能不是最好的解決方案,但它的工作原理。