2012-03-10 59 views
2

我想要一個更好的建議...更好地使用ruby特性。任何人都可以給我一個更好的解決方案來組裝這個查詢?Ruby在WHERE子句中使用帶有多個選項的查詢

@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 

太感謝你了,

回答

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

如果可能,請詳細說明如何使用.keys。謝謝! – 2012-03-10 15:57:02

1

而@xdazz答案是清潔的,這樣一來返回所需的輸出。

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

編輯:

的方法散列#鍵簡單地返回哈希鍵。這可以用來說明以下內容:

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的答案是應該使用的。

+0

請大家幫忙解釋一下,這是不同的地方,而zdazz只是鍵而已?如果xdazz沒有.keys,那該怎麼辦? – 2012-03-10 15:56:44

+0

嗯,我有!感謝你們 ! – user1261175 2012-03-10 16:20:41