Rails 3:显示表单的验证错误(不保存ActiveRecord模型) [英] Rails 3: Display validation errors for a form (not saving an ActiveRecord model)

查看:78
本文介绍了Rails 3:显示表单的验证错误(不保存ActiveRecord模型)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

道歉,如果这是一个非常普遍和/或荒谬的问题;我发誓我已经阅读了多次文档,而且一切似乎都集中在ActiveRecord上,以至于他们已经偏离了执行创建或编辑模型数据以外的功能的表单的路径.

Apologies if this is a really common and/or ridiculous question; I swear I've read over the documentation multiple times and everything seems so focused on ActiveRecord to the point they've wandered off the path of forms that do something other than create or edit model data.

例如,使用带有输入的表单来控制某些统计信息的提取和显示. Rails为我提供了什么来验证此表单的用户输入,而不会在任何记录上调用save?像这样的东西:

Take for example a form with inputs to control the extraction and display of some statistics. What does rails provide me with for validating the user input of this form, which won't be invoking save on any records? Things like:

  • :email必须是电子邮件地址
  • :num_products必须为正整数
  • :gender必须是"M"或"F"之一
  • :temperature必须介于-10和120之间
  • :email must be an email address
  • :num_products must be a positive whole number
  • :gender must be one of "M" or "F"
  • :temperature must be between -10 and 120

Etc等(大多数Web框架中标准的东西)...

Etc etc (the sort of stuff that comes standard in most web frameworks)...

Rails中是否有一些东西可以执行此任意验证,还需要一些视图助手来显示错误列表,或者一切都与ActiveRecord结合在一起?

Is there something in Rails for me to perform this arbitrary validation and some view helper to display a list of errors, or is everything coupled with ActiveRecord?

很抱歉,如果我在文档中忽略了此内容,但并没有真正覆盖它,至少到目前为止mt疲倦的眼睛可以分辨.

Apologies if I've overlooked this in the documentation, but this and this don't really cover it, at least as far as mt weary eyes can tell.

抓头

感谢罗伯的回答,这就是我的想法.我创建了一个实用程序类(恰当地命名为Validator),该类仅嵌入到我的控制器中,以用于需要它的任何内容.

Thanks to Rob's answer, here's what I've come up with. I created a utility class (aptly named Validator) which is just embedded into my controllers for anything that needs it.

module MyApp

    class Validator
        include ActiveModel::Validations
        include ActiveModel::Conversion
        extend  ActiveModel::Naming

        def initialize(attributes = {})
            super
            attributes.each { |n, v| send("#{n}=", v) if respond_to?("#{n}=") }
        end
    end

end

例如,现在在控制器中,只需定义一个内联类:

Now in the controller, for example, just define a little inline-class:

class LoginController < ApplicationController
    class AuthenticationValidator < MyApp::Validator
        attr_accessor :email
        attr_accessor :password
        validates_presence_of :email, :message => "E-mail is a required field"
        validates_presence_of :password, :message => "Password cannot be blank"
    end

    def authenticate
        if request.post?
            @validator = AuthenticationValidator.new(params)
            if @validator.valid?
                # Do something meaningful
            end
        end
    end

当逻辑更加面向控制器的恕我直言时,将每组验证规则都粘在自己的.rb中感觉有点不必要.可能有一种更简洁的方式来编写此代码,但是我对Ruby和Rails还是很陌生.

It feels a bit unnecessary to stick every single set of validation rules in their own .rb when the logic is more controller-oriented IMHO. There is probably a more succinct way to write this, but I'm pretty new to Ruby and Rails.

推荐答案

是的,可以很容易地完成.

Yes, it can be done fairly easily.

您可以为其使用验证 API.

You can use the validations API for it.

例如,这是我用于不使用ActiveRecord的应用程序的与我们联系"模型.

As an example, here is a contact us model that I use for an application that is not using ActiveRecord.

class ContactUs
  include ActiveModel::Validations
  include ActiveModel::Conversion
  extend ActiveModel::Naming

  attr_accessor :name, :email, :subject, :message
  validates_presence_of :name, :email, :message, :subject
  validates_format_of :email, :with => /\A[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}\z/
  def initialize(attributes=nil)
    attributes.each do |name, value|
      send("#{name}=", value)
    end unless attributes.nil?
  end

  def persisted?
    false
  end
end

这篇关于Rails 3:显示表单的验证错误(不保存ActiveRecord模型)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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