开发者

Rails 2.3.11 Create Model for Form And Use ActiveRecord Validation

开发者 https://www.devze.com 2023-03-12 10:18 出处:网络
In Rails 3 you simply include ActiveRecord modules in order to add validations to any non-database backed model. I want to create a model for a form (e.g. ContactForm model) and include ActiveRecord v

In Rails 3 you simply include ActiveRecord modules in order to add validations to any non-database backed model. I want to create a model for a form (e.g. ContactForm model) and include ActiveRecord valiations. But you cannot simply include the ActiveRecord modules in Rails 2.3.11. Is there any way to accomplish the same behavior as 开发者_开发问答Rails 3 in Rails 2.3.11?


If you just want to use the virtual class as a sort of validation proxy for more than one models, the following might help ( for 2.3.x, 3.x.x allows you to user ActiveModel as previously stated ):

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

this way you can include the Validations submodule, which will complain that save and save! methods are not available if you attempt to include it before defining them. Probably not the best solution, but it works.

0

精彩评论

暂无评论...
验证码 换一张
取 消