我正在尝试使用Ruby,ActiveRecord和MySQL在引号数据库中完成多字搜索.我的方式如下所示,它正在运作,但我想知道是否有更好的方法.# receives a string, splits it in a array of words, create the conditions# qu...

我正在尝试使用Ruby,ActiveRecord和MySQL在引号数据库中完成多字搜索.我的方式如下所示,它正在运作,但我想知道是否有更好的方法.
# receives a string, splits it in a array of words, create the 'conditions'
# query, and send it to ActiveRecord
def search
query = params[:query].strip.split if params[:query]
like = "quote LIKE "
conditions = ""
query.each do |word|
conditions += (like + "'%#{word}%'")
conditions += " AND " unless query.last == word
end
@quotes = Quote.all(:conditions => conditions)
end
我想知道是否有更好的方法来组成这个’条件’字符串.我也尝试使用字符串插值,例如,使用*运算符,但最终需要更多的字符串处理.提前致谢
解决方法:
首先,我强烈建议您将Model的逻辑移到模型中.不是在Controller中创建搜索逻辑,而是在Quote模式中创建一个#search方法.
class Quote
def self.search(query)
...
end
end
你的控制器变成了
# receives a string, splits it in a array of words, create the 'conditions'
# query, and send it to ActiveRecord
def search
@quotes = Quote.search(params[:query])
end
现在,回到原来的问题.您现有的搜索逻辑会犯一个非常糟糕的错误:它直接插入值,将代码打开到SQL注入.假设您使用Rails 3,您可以利用新的#where语法.
class Quote
def self.search(query)
words = query.to_s.strip.split
words.inject(scoped) do |combined_scope, word|
combined_scope.where("quote LIKE ?", "%#{word}%")
end
end
end
这是一个高级主题.我想了解combined_scope注入的内容,我建议您阅读文章The Skinny on Scopes.
沃梦达教程
本文标题为:使用Ruby和MySQL进行多字搜索


基础教程推荐
猜你喜欢
- R语言入门使用RStudio制作包含Rcpp代码的R包 2022-12-05
- R语言的一个加法函数使用介绍 2022-11-14
- 深入探究Golang中log标准库的使用 2023-07-25
- R语言向量下标和子集的使用 2022-12-10
- 解决R语言中install_github中无法安装遇到的问题 2022-11-26
- 详解swift中xcworkspace多项目管理 2023-07-05
- 汇编语言:比较指令、跳转指令、JCC的使用 2023-07-06
- R语言因子型数值转数值型的操作 2022-11-23
- ruby – 如何使用Nginx,Passenger,Sinatra创建多个位置 2023-09-20
- 如何将mysql数据库文件连接到Rails应用程序上的本地ruby 2023-09-21