Rails:如何通过包含特定字符串的字段查找 [英] Rails: How to find_by a field containing a certain string
问题描述
我有一个名为 Topic 的模型,它有一个名称作为字段.
I have a model named Topic, that has a name as a field.
所以说我有一个要搜索的词,apple.
So say I have a term I'm searching for, apple.
如果我做一个
Topic.find_by_name("apple")
我得到了一个名为 apple 的记录.这很好——但是我如何更改 find_by_name 以便它可以找到apple juice"和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?
感谢所有的回应.我想我之前应该更清楚一点,但是如果我想通过变量名称查找怎么办(显然我不会每次都想通过名称apple"查找:))?
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 :) )?
我如何操作 Topic.where 以适应此情况?所以像...
How do I manipulate Topic.where to accommodate for this? So something like...
@topic = Topic.where(......., @name)
推荐答案
我认为这样的事情应该可行:
I think something like this should work:
Topic.where("name like ?", "%apple%")
为了适应您的
Topic.where("name like ?", "%#{@search}%")
基本的字符串插值,你在字符串%%
中使用了@search
的值,所以你@search = "apple"
然后你会得到 %apple%
Basic string interpolation, you're using the value of @search
inside the string %%
, so you @search = "apple"
then you end up with %apple%
这篇关于Rails:如何通过包含特定字符串的字段查找的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!