Rails的Mongoid正则表达式在Integer字段上 [英] Rails mongoid regex on an Integer field

查看:59
本文介绍了Rails的Mongoid正则表达式在Integer字段上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些ID 214001, 214002, 215001, etc...

我想从搜索栏中自动添加ID

From a searchbar, I want autocompletion with the ID

"214"应触发ID为214001214002

"214" should trigger autocompletion for IDs 214001, 214002

显然,我不能只是做一个

Apparently, I can't just do a

scope :by_number, ->(number){
    where(:number => /#{number.to_i}/i)
}

与蒙古木偶.任何人都知道将Mongoid Integer字段与正则表达式匹配的工作方法吗?

with mongoid. Anyone know a working way of matching a mongoid Integer field with a regex ?

问题有一些线索,但是我该如何在内部执行此操作Rails吗?

This question had some clue, but how can I do this inside Rails ?

编辑:上下文应能够通过其整数ID或简短描述来查找项目:

EDIT : The context is to be able to find a project by its integer ID or its short description :

scope :by_intitule, ->(regex){ 
    where(:intitule => /#{Regexp.escape(regex)}/i)
}
# TODO : Not working !!!!
scope :by_number, ->(numero){
    where(:number => /#{number.to_i}/i)
}
scope :by_name, ->(regex){ 
    any_of([by_number(regex).selector, by_intitule(regex).selector])
}

推荐答案

链接问题中的MongoDB解决方案为:

The MongoDB solution from the linked question would be:

db.models.find({ $where: '/^124/.test(this.number)' })

您要提交给find的内容几乎一对一地映射到Mongoid:

Things that you hand to find map pretty much one-to-one to Mongoid:

where(:$where => "/^#{numero.to_i}/.test(this.number)")

在这种有限的情况下,to_i调用应可使字符串插值正常.

The to_i call should make string interpolation okay for this limited case.

请记住,这对您的数据库来说是一件非常恐怖的事情:它无法使用索引,它将扫描集合中的每个文档,...

Keep in mind that this is a pretty horrific thing to do to your database: it can't use indexes, it will scan every single document in the collection, ...

使用字符串字段可能会更好,这样您就可以进行常规的正则表达式匹配.我很确定,如果您一开始也锚定了正则表达式,MongoDB将能够使用索引.如果您确实需要将其作为数据库中的数字,则可以始终将其存储为Integer和String字段:

You might be better off using a string field so that you can do normal regex matching. I'm pretty sure MongoDB will be able to use an index if you anchor your regex at the beginning too. If you really need it to be a number inside the database then you could always store it as both an Integer and a String field:

field :number,   :type => Integer
field :number_s, :type => String

,然后有一些挂钩可以使:number_s保持最新状态,以适应:number的更改.如果执行此操作,则模式匹配范围将在:number_s处查看.像这样的预计算和复制数据在MongoDB中非常普遍,因此您不必为此感到难过.

and then have some hooks to keep :number_s up to date as :number changes. If you did this, your pattern matching scope would look at :number_s. Precomputing and duplicating data like this is pretty common with MongoDB so you shouldn't feel bad about it.

这篇关于Rails的Mongoid正则表达式在Integer字段上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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