我正在尝试使用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进行多字搜索
基础教程推荐
猜你喜欢
- Go语言实现一个Http Server框架(二) Server的抽象 2023-07-25
- go语言的魔幻旅程14-反射 2023-09-05
- golang 自然语言处理工具(gohanlp) 2023-09-05
- R语言多元线性回归实例详解 2022-12-15
- R语言使用gganimate创建可视化动图 2022-12-10
- R语言关联规则深入详解 2022-11-08
- ruby-on-rails – Nginx支持的Rails应用程序中缺少Content-Length Header 2023-09-20
- R语言histogram(直方图)的具体使用 2022-10-28
- Ruby on Rails在Ping ++ 平台实现支付 2023-07-22
- R语言学习代码格式一键美化 2022-12-05
