我对Rails比较陌生,有点惊讶这不是一个可配置的行为......至少没有一个我能找到的呢?!?我本以为99%的表单会从所有的string
& text
字段中删除的空白中受益?!?猜猜我错了...Rails 3 strip whitespace before_validation on all
无论如何,我正在寻找一种DRY方法来从Rails 3应用中的表单字段(类型:字符串&:文本)中去除所有空格。
该视图有助手自动引用(包括?)并可用于每个视图...但模型似乎没有这样的事情?!?或者他们呢?
所以目前我做这第一需要和然后包括的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/
?),它将取出参数列表(或属性),并从每个不包含特定名称的属性中删除空格(.strip!
?)。
可能重复(http://stackoverflow.com/questions/4272028/is-there-a-干燥的方式使用条带的所有参数,当创建一个新的模型在轨道) – 2010-11-28 04:16:51
你可以把它放进一个帮手,并将其包含在你的模型 – 2010-11-28 02:43:20