SQL Rails:如何通过包含特定字符串的字段查找

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9708409/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 14:50:40  来源:igfitidea点击:

Rails: How to find_by a field containing a certain string

sqlruby-on-railsruby-on-rails-3ruby-on-rails-3.1

提问by varatis

I have a model named Topic, that has a name as a field.

我有一个名为 Topic 的模型,它有一个名称作为字段。

So say I have a term I'm searching for, apple.

所以说我有一个我正在寻找的术语,苹果。

If I do a

如果我做一个

Topic.find_by_name("apple")

I get a record back with the name apple. That's good -- but how do I change find_by_name so that it can find "apple juice" as well as "apple" -- basically, find names that contain the original query or exactly match the original query?

我得到了一个名字为苹果的记录。这很好——但是我如何更改 find_by_name 以便它可以找到“apple juice”和“apple”——基本上,查找包含原始查询或与原始查询完全匹配的名称?

Edit:Thanks for all the response. I guess I should've been a little more clear earlier, but what if I want to find by a variable name (obviously I'm not going to want to find by the name "apple" everytime :) )?

编辑:感谢所有的回应。我想我应该早些时候更清楚一点,但是如果我想通过变量名查找怎么办(显然我不会每次都想通过名称“apple”来查找:))?

How do I manipulate Topic.where to accommodate for this? So something like...

我如何操作 Topic.where 来适应这个?所以像...

@topic = Topic.where(......., @name)

回答by Deleteman

I think something like this should work:

我认为这样的事情应该有效:

Topic.where("name like ?", "%apple%")

To accomodate for your edit:

为了适应您的编辑:

Topic.where("name like ?", "%#{@search}%")

Basic string interpolation, you're using the value of @searchinside the string %%, so you @search = "apple"then you end up with %apple%

基本串插,你正在使用的值@search的字符串里面%%,所以你@search = "apple"那你结了 %apple%

回答by ScottJShea

Looks like in Rails 3you would want to use the where:

看起来在Rails 3 中你会想要使用 where:

Topic.where("name ILIKE ?", "%apple%")

回答by Alisher Ulugbekov

Don't put string directly like that. Its called SQL injection. You should instead use .where:

不要像那样直接放字符串。它被称为 SQL 注入。你应该改用.where

Topic.where("name like '?%' ", params[:name])

回答by Szymon Rut

With PostgreSQL you can also use match operators:

使用 PostgreSQL,您还可以使用匹配运算符

Topic.where("name ~* ?", @search)

回答by asitmoharna

Try

尝试

Topic.where("name like ?",'%apple%')
Topic.find(:all, :conditions => ["name like ?","%apple%"])