ruby-on-rails - 如何在 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,任何提示都会很有帮助。
解决方案
您可以使用类似查询来执行此操作。把它放在一个范围内,这样它就很容易获得。
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
我还建议您将数据“标准化”存储,不带破折号,只存储数字。这更易于使用,并且可以更改接受的格式而无需更改所有数据。在装饰器中格式化它们。
推荐阅读
- java - 在 UCanAccess 中使用 order by 订购 ID
- python - 订购共面点以绘制它们
- amazon-web-services - 如何找出我需要为 CLI 命令授予哪些 AWS 操作?
- python - 当我使用 Django 模板标签循环时数据不显示
- c# - 将 .Net Standard 2.0 迁移到 .Net Core 2.2
- neo4j - 将关系(及其属性)克隆到新节点
- uwp - 在 UWP 中使用 Windows.Storage 命名空间获取内部驱动器
- sql - Full Outer Join 不包括双方的所有记录
- php - Date() 不输出所需的答案
- javascript - 检查索引之一中的字段之一是否为空