首页 > 解决方案 > 如何在 Rails 控制台中根据列格式过滤模型

问题描述

我一直在努力处理基于列格式过滤掉 A 模型(候选)的客户请求

我面临的问题是该列输入 SSN 或 EIN。SSN 的格式是 (xxx-xx-xxxx) EIN 的格式是 (xx-xxxxxxx)

我的候选人表包含字段 ssn_or_ein ,它采用这两个中的任何一个。

例如:candidate111.ssn_or_ein => 111-11-1111 Candidate222.ssn_or_ein => 22-2222222

我已经尝试获取所有 4000 个帐户,但我认为这不是开发人员应该采用的方法。

我仍在学习 Rails,任何提示都会很有帮助。

标签: ruby-on-railsrubyruby-on-rails-5rails-console

解决方案


您可以使用类似查询来执行此操作。把它放在一个范围内,这样它就很容易获得。

class Candidate < ApplicationRecord
  scope with_ein -> { where( "ssn_or_ein like ?", "__-_______" }
  scope with_ssn -> { where( "ssn_or_ein like ?", "___-__-____" }
end

ssn_or_ein但是,如果没有正确索引,这可能会变慢。


考虑将它们存储在两个不同的列中。这使得验证和查询更简单。仅当您只需要TIN 纳税人信息号时才将它们放在一起。

class Candidate < ApplicationRecord
  scope with_ein -> { where.not( ein: nil ) }
  scope with_ssn -> { where.not( ssn: nil ) }

  EIN_RE = %r{^\d{2}-\d{7}$}
  SSN_RE = %r{^\d{3}-\d{2}-\d{4}$}
  validates :ein, format: { with: EIN_RE }, allow_nil: true
  validates :ssn, format: { with: SSN_RE }, allow_nil: true

  def tin
    ssn || ein
  end

  class << self
    def find_by_tin(tin)
      where( ssn: tin ).or( where(ein: tin) )
    end
  end
end

我还建议您将数据“标准化”存储,不带破折号,只存储数字。这更易于使用,并且可以更改接受的格式而无需更改所有数据。在装饰器中格式化它们。


推荐阅读