在没有模型的情况下在 Rails 中进行验证 [英] Validation in Rails without a model

查看:54
本文介绍了在没有模型的情况下在 Rails 中进行验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个允许用户向电子邮件发送消息的表单,我想为其添加验证.我没有这个模型,只有一个控制器.我应该如何在 Rails 中执行此操作?

I have a form that allows the user to send a message to an email, and I want to add validation to it. I do not have a model for this, only a controller. How should I do this in Rails?

我正在考虑在控制器中进行验证,并使用 闪光 对象.有没有更好的方法来做到这一点?

I was considering doing the validation in the controller, and displaying the errors to the user using the flash object. Is there a better way of doing this?

推荐答案

最好的方法是将您的伪模型包装在一个类中,并在那里添加验证.Rails 方式规定您不应将模型行为放在控制器上,唯一的验证应该是与请求本身相关的验证(身份验证、授权等)

The best approach would be to wrap up your pseudo-model in a class, and add the validations there. The Rails way states you shouldn't put model behavior on the controllers, the only validations there should be the ones that go with the request itself (authentication, authorization, etc.)

在 Rails 2.3+ 中,您可以包含 ActiveRecord::Validations,但有一个小缺点,即您必须定义 ActiveRecord 层期望的一些方法.请参阅这篇文章以了解更深入的信息解释.以下代码改编自该帖子:

In Rails 2.3+, you can include ActiveRecord::Validations, with the little drawback that you have to define some methods the ActiveRecord layer expects. See this post for a deeper explanation. Code below adapted from that post:

require 'active_record/validations'

class Email

  attr_accessor :name, :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

  # Required method stubs
  def save
  end

  def save!
  end

  def new_record?
    false
  end

  def update_attribute
  end

  # Mix in that validation goodness!
  include ActiveRecord::Validations

  # Validations! =)
  validates_presence_of :name
  validates_format_of :email, :with => SOME_EMAIL_REGEXP
end

在 Rails3 中,你有那些 sexy验证供您使用:)

In Rails3, you have those sexy validations at your disposal :)

这篇关于在没有模型的情况下在 Rails 中进行验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆