-1

letters在 mysql 数据库的列中有以下数据。我把它们保存在varchar

letters
["a","b"]
["a","b","d"]
["a","d"]
["d","c","e"]
["e","c","f"]
["c","f"]
["f","e"]

我正在尝试匹配一些元素。当我有params[:lttrs]as"a"时,我想返回:

["a","b"]
["a","b","d"]
["a","d"]

当我有params[:lttrs]as"c,e"时,我想返回:

["d","c","e"]
["e","c","f"]

我的尝试是检索所有行,然后将它们中的每一行与 匹配include?('a'),但是这样,我一次只能做一个元素。那是方法吗?

4

2 回答 2

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

letter_found = 不管模型.where(查询)

显然,您需要确保参数的处理比这更安全,但这应该会让您上路。

于 2013-05-08T07:18:57.240 回答
0

您可以将LIKE运算符与通配符匹配一起使用。此解决方案将比使用 ruby​​ 更快。但是如果你有一张大桌子,它会很慢。如果您提供有关数据设计原因的更多详细信息,我们将能够建议替代方法。

like_params = params[:lttrs].split(",").map{|letter| "%#{letter}%"}
like = like_params.map{ "LIKE ?"}.join(" OR ")
Model.where(like, like_params)
于 2013-05-08T07:14:06.460 回答