在所有表单上使用Rails 3删除空格before_validation [英] Rails 3 strip whitespace before_validation on all forms

查看:111
本文介绍了在所有表单上使用Rails 3删除空格before_validation的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Rails还是比较陌生,这让我感到有些惊讶,这不是一种可配置的行为……至少我还没有找到一个?我本以为99%的表单将从所有 string & text 字段?!?猜猜我错了...

I'm relatively new to Rails and a bit surprised this isn't a configurable behavior...at least not one I've been able to find yet?!? I would have thought that 99% of forms would benefit from whitespace being trimmed from all string & text fields?!? Guess I'm wrong...

无论如何,我正在寻找一种DRY方式来从表单字段(类型为:string&:text)中剥离所有空格。在Rails 3应用中。

Regardless, I'm looking for a DRY way to strip all whitespace from form fields (of type :string & :text) in a Rails 3 app.

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

The Views have Helpers that are automatically referenced (included?) and available to each view...but Models don't seem to have such a thing?!? Or do they?

所以目前我正在做以下 需要然后然后 包括 whitespace_helper(又名WhitespaceHelper)。但这对我来说似乎还不是很干,但是它可以工作...

So currently I doing the following which first requires and then includes the whitespace_helper (aka WhitespaceHelper). but this still doesn't seem very DRY to me but it works...

ClassName.rb:

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:

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

I guess I'm looking for a single (D.R.Y.) method (class?) to put somewhere (lib/ ?) that would take a list of params (or attributes) and remove the whitespace (.strip! ?) from each attribute w/out being named specifically.

推荐答案

创建 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 3删除空格before_validation的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆