Ruby在WHERE子句中使用带有多个选项的查询

时间:2012-03-10 15:29:19

标签: ruby where

我想更好的建议......更好地使用ruby功能。任何人都可以给我一个更好的解决方案来组装这个查询吗?

@conditions = ""
if(ratings["G"] == "1")
  @conditions += " 'G' "

end
if(ratings["PG"] == "1")
  @conditions += " OR rating = 'PG' "

end
if(ratings["PG-13"] == "1")
  @conditions += " OR rating = 'PG-13' "

end
if(ratings["R"] == "1")
  @conditions += " OR rating = 'R' "

end

@movies = Movie.where("rating = "+ @conditions)

return @movies

非常感谢你,

2 个答案:

答案 0 :(得分:5)

Movie.where(:rating => ratings.select({|k,v| v == "1"}).keys)

答案 1 :(得分:1)

虽然@xdazz答案更清晰,但这种方式会返回所需的输出。

@conditions = ""
ratings.each do |k, v|
  @conditions << (@conditions.empty? ? "rating = '#{k}'" : " OR rating = '#{k}'") if v == "1"
end
@movies = Movie.where(@conditions)

修改

方法Hash#keys只返回哈希的键。这可以通过以下方式说明:

p ratings.select { |k,v| v == "1" }.keys
# => ["G", "PG", "PG-13", "R"]
p ratings.select { |k,v| v == "1" }
# => {"G"=>"1", "PG"=>"1", "PG-13"=>"1", "R"=>"1"}

虽然上面的方法会返回更像SQL的字符串:

p @conditions 
# => "rating = 'G' OR rating = 'PG' OR rating = 'PG-13' OR rating = 'R'"

最后,@ xdazz方法可以重写为以下内容,以便获得相同的输出:

p "rating = '" + ratings.select { |k,v| v == "1" }.keys.join("' OR rating = '") + "'"
# => "rating = 'G' OR rating = 'PG' OR rating = 'PG-13' OR rating = 'R'"

编辑2: 为了清楚原始问题是否与Rails相关,@ xdazz答案是应该使用的答案。