6

我对 Rails 比较陌生,有点惊讶这不是一种可配置的行为……至少我还没有找到?!?我原以为 99% 的表单会受益于从所有string&text字段中修剪空白?!?估计我错了...

无论如何,我正在寻找一种 DRY 方法来从 Rails 3 应用程序中的表单字段(类型:string 和:text)中删除所有空格。

视图具有自动引用(包括?)并且可用于每个视图的助手......但是模型似乎没有这样的东西?!?还是他们?

因此,目前我执行以下操作,首先需要然后包含 whitespace_helper又名WhitespaceHelper)。但这对我来说似乎仍然不是很干燥,但它有效......

类名.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! 从每个属性中删除空格(?)没有被特别命名.

4

3 回答 3

8

创建一个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
于 2010-11-28T06:33:04.057 回答
1

为 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
于 2013-10-04T14:24:18.960 回答
0

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

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

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

MyModel < MyActiveRecordBase
  # stuff
end
于 2012-01-18T16:15:21.123 回答