我在mysql数据库的letters
列中有以下数据。我将它们保存在varchar
:
letters
["a","b"]
["a","b","d"]
["a","d"]
["d","c","e"]
["e","c","f"]
["c","f"]
["f","e"]
我正在尝试匹配一些元素。当我params[:lttrs]
为"a"
时,我想返回:
["a","b"]
["a","b","d"]
["a","d"]
当我params[:lttrs]
为"c,e"
时,我想返回:
["d","c","e"]
["e","c","f"]
我的尝试是检索所有行,然后将每个行与include?('a')
匹配,但有了这个,我一次只能做一个元素。这是方法吗?
答案 0 :(得分:0)
您可以将LIKE
运算符与通配符匹配使用。这个解决方案比使用ruby更快。但如果你有一张大桌子,它会很慢。如果您提供有关数据设计原因的更多详细信息,我们将能够建议其他方法。
like_params = params[:lttrs].split(",").map{|letter| "%#{letter}%"}
like = like_params.map{ "LIKE ?"}.join(" OR ")
Model.where(like, like_params)
答案 1 :(得分:0)
你可以尝试做类似的事情:
query = "letters "
r = 1
letters_arr = params[:lttrs].split(",")
letters_arr.each do |l|
if r == 1:
query << " like '%#{l}%'"
else
query << " or like '%#{l}%'"
end
end
letters_found = WhateverModel.where(查询)
显然你需要确保params的安全处理比这更安全,但这应该可以让你上路。