【问题标题】:Rails 4 Tableless Model with Validations带有验证的 Rails 4 无表模型
【发布时间】:2015-03-10 17:59:29
【问题描述】:

在 rails 4.0.5 中,我设置了一个无表模型。所以我有一个接受信息的表格,但是当我尝试验证信息时它确实有效。即使该字段已填写,验证也会在所有字段上返回“不能为空白”。我做错了什么。

表格

 = 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"}}

【问题讨论】:

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


    【解决方案1】:

    我不知道出了什么问题,但我猜这与您覆盖 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."]}
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多