在保存到DB之前删除掩码

时间:2016-12-29 17:04:10

标签: ruby-on-rails ruby

我有一个JavaScript来掩盖表单中的值。我试图删除这个掩码,然后将其保存在db中,但我有问题

模特:

class Partner < ApplicationRecord
  belongs_to :address, dependent: :destroy
  has_many :dependents
  accepts_nested_attributes_for :address
  
  # Validations #
  # Validates presence of some attributes #
  validates_presence_of :registry_number, :name, :secretary, :position, :base_salary, :rg, :cpf, :birthday, :email, :union_admission, :start_date
  validates :registry_number, numericality: {only_integer: true} 
  
  # Validates the size of some attributes #
  validates :registry_number, length: {maximum: 5}
  validates :cpf, length: {is: 11}
  validates :rg, length: {is: 9}
  validates :phone_number, length: {maximum: 11}


  :cpf.gsub(/[.\/]/, '')

end

错误

undefined method `gsub' for :cpf:Symbol

Extracted source (around line #18):
16
17
18
19
20
              


  :cpf.gsub(/[.\/]/, '')

end

我该如何解决?

2 个答案:

答案 0 :(得分:0)

gsub是字符串上的一种方法,因此您可以先在符号上调用.to_s

答案 1 :(得分:0)

正如错误消息所示,行:cpf.gsub(/[.\/]/, '')是问题所在。首先,您在符号gsub上调用方法:cpf,并且该方法不存在。在irb中尝试。

其次,即使情况并非如此,也不会有任何区别 - 代码只会在类加载时运行一次,并且每次都不会运行你保存了一个新的Partner。每次创建新对象时都需要添加before_validation callback来运行代码,如下所示:

class Partner
  #...
  before_validation :unmask_cpf

  #...

  private

  def unmask_cpf
    cpf = cpf.gsub(/[.\/]/, '')
  end
end