user1261175
user1261175

Reputation: 11

Ruby using queries with multiple options in WHERE clause

I'd like to a better suggestion ... to use the ruby features better. Can anyone give a me a better solution to assemble this query ?

@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

Thank you so much,

Upvotes: 2

Views: 357

Answers (2)

Jakobinsky
Jakobinsky

Reputation: 1294

while @xdazz answer is cleaner, this way returns the required output.

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

EDIT:

The method Hash#keys simply return the keys of the hash. This can be illustrated with the following:

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"}

While the method above would return a more SQL like string:

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

Finally, @xdazz method can be rewritten to the following, in order to achive the same output:

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

EDIT 2: Just to be clear if the original question is regarding Rails, @xdazz answer is the one that should be used.

Upvotes: 1

xdazz
xdazz

Reputation: 160843

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

Upvotes: 5

Related Questions