问题描述
我实现一个简单的搜索功能,应检查字符串无论是在用户名,姓氏和FIRST_NAME。我已经看到了这个ActiveRecord的方法在一个旧RailsCast:
I'm implementing a simple search function that should check for a string in either the username, last_name and first_name. I've seen this ActiveRecord method on an old RailsCast:
http://railscasts.com/episodes/37-simple-search-form
find(:all, :conditions => ['name LIKE ?', "%#{search}%"])
但我怎么做它,以便它搜索的名字,姓氏和名字的关键字并返回记录,如果该领域中的一个匹配的词?
But how do I make it so that it searches for the keyword in name, last_name and first name and returns the record if the one of the fields matched the term?
我也想知道,如果在RailsCast的code是容易出现SQL注入?
I'm also wondering if the code on the RailsCast is prone to SQL injections?
非常感谢!
推荐答案
我认为您的型号名称是模型 - 只是与你的真实型号名称替换它,当你做了实际的查询:
I assumed your model name is Model - just replace it with your real model name when you do the actual query:
Model.where("name LIKE ? OR last_name LIKE ? OR first_name LIKE ?", "%#{search}%","%#{search}%","%#{search}%")
关于你的担心SQL注入 - 两个code片段是免疫的SQL注入。只要你不直接嵌入字符串到您的WHERE子句中你的罚款。用于注射的多发code的一个例子是:
About your worries about SQL injections - both of code snippets are immune to SQL injections. As long as you do not directly embed strings into your WHERE clause you are fine. An example for injection-prone code would be:
Model.where("name LIKE '#{params[:name]}'")
这篇关于Rails的ActiveRecord的 - 搜索上的多个属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!