【问题标题】:Rails 2.3.11 Create Model for Form And Use ActiveRecord ValidationRails 2.3.11 为表单创建模型并使用 ActiveRecord 验证
【发布时间】:2011-06-13 21:47:43
【问题描述】:

在 Rails 3 中,您只需包含 ActiveRecord 模块即可向任何非数据库支持的模型添加验证。我想为表单创建一个模型(例如 ContactForm 模型)并包含 ActiveRecord valiations。但是你不能简单地在 Rails 2.3.11 中包含 ActiveRecord 模块。有什么方法可以在 Rails 2.3.11 中完成与 Rails 3 相同的行为?

【问题讨论】:

    标签: ruby-on-rails ruby forms activerecord activemodel


    【解决方案1】:

    如果您只想将虚拟类用作多个模型的一种验证代理,以下可能会有所帮助(对于 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! 方法,它将抱怨它们不可用。可能不是最好的解决方案,但它确实有效。

    【讨论】:

      猜你喜欢
      • 2011-07-20
      • 1970-01-01
      • 2011-08-17
      • 2011-04-20
      • 1970-01-01
      • 1970-01-01
      • 2012-07-28
      • 1970-01-01
      • 2012-02-25
      相关资源
      最近更新 更多