ruby-on-rails - Rails 2.3.11 为表单创建模型并使用 ActiveRecord 验证

标签 ruby-on-rails ruby forms activerecord activemodel

在 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 子模块,如果您在定义它们之前尝试包含它,它将提示 savesave! 方法不可用。可能不是最好的解决方案,但它确实有效。

关于ruby-on-rails - Rails 2.3.11 为表单创建模型并使用 ActiveRecord 验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6336783/

相关文章:

ruby-on-rails - 安装 RVM 后未找到 RVM

ruby - 无需插件即可在 Jekyll 中生成站点地图

ruby-on-rails - 推送到 heroku 时,rake 中止不接受 TCP/IP 连接

ruby-on-rails - Rails + Postgres fe_sendauth : no password supplied

ruby - 为什么这些代码行没有返回任何结果?

Javascript onchange 事件。选择/选项 html 下拉输入

javascript - Jquery Click函数从不同的表单获取参数

html - PayPal:选择具有数量的多个项目

ruby-on-rails - 在 Rails form_for 辅助字段中使用 ParsleyJS

Ruby:测试未​​运行