Adam Zerner
Adam Zerner

Reputation: 19248

Querying in Rails with multiple hash conditions

I'm referring to hash conditions as described here. Could you use multiple types of hash conditions? Like equality and subset? I tried it, and it's giving me a syntax error:

@colleges = College.where(category: "#{@university_type}" and "us_news_ranking < #{@rank_low}").first

Is it possible to do this, or is my code just wrong?

Upvotes: 0

Views: 2166

Answers (2)

Vitalyp
Vitalyp

Reputation: 1089

You can combine both conditions:

@colleges = College.where("category = ? AND us_news_ranking < ?", 
              @university_type, 
              @rank_low).first

Also, sometimes preffer to use hash variables:

@colleges = College.where("category = :type AND us_news_ranking < :rank",
              type: @university_type, 
              rank: @rank_low).first

Upvotes: 0

user229044
user229044

Reputation: 239382

Is it possible to do this, or is my code just wrong?

Your code is just wrong. and isn't involved in this; if you want several conditions, supply several several keys/values to where. In this case, you need two where calls - one for the equality condition, and one for the less-than condition.

You also should never interpolate values directly into your string. Use placeholders so ActiveRecord can escape them and prevent SQL injection.

@colleges = College.where(category: @university_type).where("us_news_ranking < ?", @rank_low).first

Upvotes: 4

Related Questions