Rails 4带有验证的无表模型

时间:2015-03-10 17:59:30

标签: ruby validation ruby-on-rails-4 activerecord model

在rails 4.0.5中,我设置了一个无表格模型。所以我有一个获取信息的表单,但是当我尝试验证信息时它会起作用。验证将返回' canot为空白'即使字段已填满,也会在所有字段上显示。我做错了什么。

形式

 = form_for @bank do |f|
   = f.text_field :first_name
   = f.text_field :account
   = f.text_field :routing
   = f.text_field :zip
   %button{:type => "submit"} Submit

控制器

 class BanksController < ApplicationController

   def new
     @bank = Bank.new
   end

   def create  
     @bank = Bank.new(params[bank_params])
     if @bank.valid?  
     # etc.... 
   end  
 end

模型

 class Bank < ActiveRecord::Base  
   def self.columns() @columns ||= []; end  
   def self.column(name, sql_type = nil, default = nil, null = true)  
     columns << ActiveRecord::ConnectionAdapters::Column.new(name.to_s, default, sql_type.to_s, null)  
   end  

     column :first_name, :string 
     column :account,    :int
     column :routing,    :int
     column :zip,        :int

     VALID_NUM_REGEX = /\A[+-]?\d+\z/    

     validates :first_name, presence: true
     validates :account, presence: true, format: { with: VALID_NUM_REGEX }, length:  { minimum: 4 }
     validates :routing, presence: true, format: { with: VALID_NUM_REGEX }, length:  { minimum: 4 }
 end  

控制台

 Started POST "/banks" for 127.0.0.1 at 2015-03-09 11:39:40 -0400
  Processing by BanksController#create as HTML
  Parameters: {"utf8"=>"✓","authenticity_token"=>"..=","bank"=>{"first_name"=>"Alain", "account"=>"1234", "routing"=>"4321","zip"=>"11413"}}

1 个答案:

答案 0 :(得分:2)

我不知道什么是错的,但我的猜测是它与你的columnscolumn重叠有关。我强烈建议您使用普通的Ruby对象,然后包含ActiveModel :: Validations。

http://api.rubyonrails.org/classes/ActiveModel/Validations.html

从该页面开始:

class Person
  include ActiveModel::Validations

  attr_accessor :first_name, :last_name

  validates_each :first_name, :last_name do |record, attr, value|
    record.errors.add attr, 'starts with z.' if value.to_s[0] == ?z
  end
end

它为您提供了从Active Record中了解的完整标准验证堆栈:

person = Person.new
person.valid?                   # => true
person.invalid?                 # => false

person.first_name = 'zoolander'
person.valid?                   # => false
person.invalid?                 # => true
person.errors.messages          # => {first_name:["starts with z."]}