如何在Rails控制台中基于列格式过滤模型



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

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

我的候选表包含字段ssn_or_ein,它接受以下两个中的任意一个。

为例:candidate111。ssn_or_ein =比;111-11-1111candidate222。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

我还建议您存储"规范化"的数据,不使用破折号,只有数字。这样操作起来更简单,并且可以在不更改所有数据的情况下更改所接受的格式。

最新更新