在 Rails 3 中,您只需包含 ActiveRecord 模块即可向任何非数据库支持的模型添加验证。我想为表单创建一个模型(例如 ContactForm 模型)并包含 ActiveRecord 变量。但是您不能简单地将 ActiveRecord 模块包含在 Rails 2.3.11 中。有什么方法可以在 Rails 2.3.11 中实现与 Rails 3 相同的行为吗?
最佳答案
如果您只想将虚拟类用作一种以上模型的验证代理,以下内容可能会有所帮助(对于 2.3.x,3.x.x 允许您使用 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!
方法不可用。可能不是最好的解决方案,但它确实有效。
关于ruby-on-rails - Rails 2.3.11 为表单创建模型并使用 ActiveRecord 验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6336783/