Rails: How to find_by a field containing a certain string

怎甘沉沦 提交于 2019-11-29 21:18:29

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%

ScottJShea

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

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

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)

Try

Topic.where("name like ?",'%apple%')
Topic.find(:all, :conditions => ["name like ?","%apple%"])
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!