简体   繁体   English

Rails ActiveRecord查询,其中“”,“ _”和“-”可互换

[英]Rails ActiveRecord query where “ ”, “_”, and “-” are interchangable

My goal is to write a Model.find_by_name("foo-bar"), would return a record in the database with the name "foo bar"). 我的目标是编写一个Model.find_by_name(“ foo-bar”),将在数据库中返回一个名称为“ foo bar”)的记录。 I'm struggling to find any information on how this might be accomplished. 我正在努力寻找有关如何实现此目标的任何信息。 I'm using postgresql. 我正在使用postgresql。 Thanks! 谢谢!

You could try using regular expressions to do this: 您可以尝试使用正则表达式来执行此操作:

to_match = "foo_bar".sub(/[ \-\_]/, '[ \-\_]')

Model.where("'name' ~ ?", to_match)

At least that's the general idea. 至少那是一般的想法。 These kinds of searches will be a lot slower on large tables. 在大型表上,这类搜索会慢很多。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM