Ruby on rails Rails 2.3.11为表单创建模型并使用ActiveRecord验证
在Rails3中,您只需包括ActiveRecord模块,以便向任何非数据库支持的模型添加验证。我想为表单创建一个模型(例如ContactForm模型),并包含ActiveRecord有效性。但您不能简单地将ActiveRecord模块包含在Rails 2.3.11中。是否有任何方法可以实现与Rails 2.3.11中Rails 3相同的行为?如果您只想将虚拟类用作多个模型的一种验证代理,以下内容可能会有所帮助(对于2.3.x,3.x.x允许您如前所述使用ActiveModel): 通过这种方式,您可以包含Validations子模块,它将抱怨Ruby on rails Rails 2.3.11为表单创建模型并使用ActiveRecord验证,ruby-on-rails,ruby,forms,activerecord,activemodel,Ruby On Rails,Ruby,Forms,Activerecord,Activemodel,在Rails3中,您只需包括ActiveRecord模块,以便向任何非数据库支持的模型添加验证。我想为表单创建一个模型(例如ContactForm模型),并包含ActiveRecord有效性。但您不能简单地将ActiveRecord模块包含在Rails 2.3.11中。是否有任何方法可以实现与Rails 2.3.11中Rails 3相同的行为?如果您只想将虚拟类用作多个模型的一种验证代理,以下内容可能会有所帮助(对于2.3.x,3.x.x允许您如前所述使用ActiveModel): 通过这种方式
save
和save如果在定义方法之前尝试包含它,则代码>方法不可用。也许不是最好的解决方案,但它是有效的
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