Rails 3 strip whitespace before_validation on all forms

别说谁变了你拦得住时间么 提交于 2019-12-04 06:29:19

Create a before_validation helper as seen here

module Trimmer
  def trimmed_fields *field_list  
    before_validation do |model|
      field_list.each do |n|
        model[n] = model[n].strip if model[n].respond_to?('strip')
      end
    end
  end
end

require 'trimmer'
class ClassName < ActiveRecord::Base
  extend Trimmer
  trimmed_fields :attributeA, :attributeB
end

Use the AutoStripAttributes gem for Rails. it'll help you to easily and cleanly accomplish the task.

class User < ActiveRecord::Base
 # Normal usage where " aaa   bbb\t " changes to "aaa bbb"
  auto_strip_attributes :nick, :comment

  # Squeezes spaces inside the string: "James   Bond  " => "James Bond"
  auto_strip_attributes :name, :squish => true

  # Won't set to null even if string is blank. "   " => ""
  auto_strip_attributes :email, :nullify => false
end

Note I haven't tried this and it might be a crazy idea, but you could create a class like this:

MyActiveRecordBase < ActiveRecord::Base
  require 'whitespace_helper'  
  include WhitespaceHelper
end

... and then have your models inherit from that instead of AR::Base:

MyModel < MyActiveRecordBase
  # stuff
end
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!