Rails 3在所有表单上删除before_validation的空格
我对Rails相对较新,有点惊讶这不是一个可配置的行为……至少没有一个我能找到的?!? 我原以为99%的表单会受益于从所有string
和text
字段中修剪的空白?!? 猜猜我错了……
无论如何,我正在寻找一种干燥的方法来从Rails 3应用程序中的表单字段(类型:string&:text)中删除所有空格。
视图有自动引用(包含?)并可用于每个视图的助手……但模型似乎没有这样的东西?!? 或者他们呢?
所以目前我做的是首先 要求的 , 然后 包括 whitespace_helper(又名WhitespaceHelper)。 但这对我来说似乎仍然不是很干,但它有效……
ClassName.rb:
require 'whitespace_helper' class ClassName < ActiveRecord::Base include WhitespaceHelper before_validation :strip_blanks ... protected def strip_blanks self.attributeA.strip! self.attributeB.strip! ... end
LIB / whitespace_helper.rb:
module WhitespaceHelper def strip_whitespace self.attributes.each_pair do |key, value| self[key] = value.strip if value.respond_to?('strip') end end
我想我正在寻找一个单一的(DRY)方法(类?)来放置一个( lib/
?),它将获取一个params(或属性)列表并从每个属性w中删除空格( .strip!
) / out被具体命名。
创建一个before_validation
帮助器,如此处所示
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
对Rails使用AutoStripAttributes gem 。 它将帮助您轻松,干净地完成任务。
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
注意我没有试过这个,这可能是一个疯狂的想法,但你可以创建一个这样的类:
MyActiveRecordBase < ActiveRecord::Base require 'whitespace_helper' include WhitespaceHelper end
...然后让你的模型inheritance而不是AR :: Base:
MyModel < MyActiveRecordBase # stuff end