0

我有一个包含主题和消息的简单联系表,我想验证它以防止出现空白电子邮件。

ActionMailer 不支持验证。我应该把它放在哪里(即在一个单独的模型中或直接在控制器中)?

更新:在非 ActiveRecord 模型中实现验证的最佳方法是什么?

4

3 回答 3

1

这有帮助吗?http://forums.site5.com/showthread.php?t=18522

于 2009-07-09T13:47:16.610 回答
1

在 Rails 3 中,他们将验证从 ActiveRecord 分离到 ActiveModel。因此,如果您使用 Rails 或在您的项目中至少有 ActiveModel gem 和 bundler 或任何您喜欢的方法,您可以在任何类中包含 ActiveModel::Validations。这是一个示例类(请注意,Bundler 需要我使用 ActiveModel):

class ContactUs::Contact
  include ActiveModel::Validations

  attr_accessor :email, :message

  validates :email,   :format => { :with => /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i },
                      :presence => true
  validates :message, :presence => true

  def initialize(attributes = {})
    attributes.each do |key, value|
      self.send("#{key}=", value)
    end
    @attributes = attributes
  end

  def read_attribute_for_validation(key)
    @attributes[key]
  end

  def save
    if self.valid?
      ContactUs::ContactMailer.contact_email(self).deliver
      return true
    end
    return false
  end
end

该示例来自我编写的ContactUs的 Contact Form Rails 3+ 引擎,如果您在实现中遇到任何其他问题,您可以在 Github 上浏览代码,如果您的应用程序不太自以为是,请使用 Gem。

于 2011-07-18T01:42:55.213 回答
0

也许这可以帮助你:http ://activeform.rubyforge.org/

于 2009-07-09T13:48:16.720 回答