我正在尝试使用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进行多字搜索


基础教程推荐
猜你喜欢
- 浅析ELF转二进制允许把 Binary 文件加载到任意位置 2023-07-06
- R语言-修改(替换)因子变量的元素操作 2022-11-26
- Swift初始化器与可选链的使用方法介绍 2023-07-08
- R语言绘制折线图实例分析 2022-11-21
- ruby on rails validates 2023-09-22
- win10下使用virtualbox + vagrant配置ruby开发机环境 2023-07-23
- Swift中重写和重载的使用与对比总结 2023-07-05
- R语言 ggplot2改变柱状图的顺序操作 2022-11-17
- ruby-on-rails-为使用Rails 4,nginx和乘客的用户设置自定义域 2023-09-21
- Ruby3多线程并行Ractor使用方法详解 2023-07-23