在Rails 3中,您只需包含ActiveRecord模块,以便为任何非数据库支持的模型添加验证。我想为表单创建一个模型(例如ContactForm模型)并包含ActiveRecord值。但是你不能简单地在Rails 2.3.11中包含ActiveRecord模块。有没有办法在Rails 2.3.11中实现与Rails 3相同的行为?
答案 0 :(得分: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
通过这种方式,您可以包含Validations子模块,如果您在定义它们之前尝试包含它,则会抱怨save
和save!
方法不可用。可能不是最好的解决方案,但它确实有效。