2010-11-28 52 views
6

我对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!?)。

+0

可能重复(http://stackoverflow.com/questions/4272028/is-there-a-干燥的方式使用条带的所有参数,当创建一个新的模型在轨道) – 2010-11-28 04:16:51

+0

你可以把它放进一个帮手,并将其包含在你的模型 – 2010-11-28 02:43:20

回答

7

创建before_validation助手所看到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 
0

注意我没有尝试这样做,它可能是一个疯狂的想法,但你可以创建一个类是这样的:

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

。 ..然后让您的模型继承而不是AR :: Base:

MyModel < MyActiveRecordBase 
    # stuff 
end 
1

U请参阅AutoStripAttributes gem for Rails。它会帮助你轻松干净地完成任务。

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 
的[有没有使用带所有一个干法?:创建在Rails的新车型时PARAMS]