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

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

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

如果我做一个

Topic.find_by_name("apple")

我得到了一个记录与名称苹果回来。这很好——但是我如何更改 find _ by _ name 以便它能够查找“ apple Juice”和“ apple”——基本上就是查找包含原始查询或与原始查询完全匹配的名称?

编辑: 谢谢你的回应。我想我之前应该说得更清楚一点,但是如果我想通过变量名来查找(显然我不想每次都通过名称“ apple”来查找:) ,那该怎么办呢?

我如何操作 Topic.where 来适应这种情况? 比如..。

@topic = Topic.where(......., @name)
83109 次浏览

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 @search inside the string %%, so you @search = "apple" then you end up with %apple%

Try

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

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

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

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

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

With PostgreSQL you can also use match operators:

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