只有在定义了变量的情况下,如何才能在Rails中查询?

时间:2014-03-11 03:59:21

标签: ruby-on-rails

考虑以下问题:@colleges = College.where(category: @university_type).where("us_news_ranking <= ? AND size <= ?", @rank, @enrollment)

我将其用于高级搜索,我希望允许用户根据特定条件进行过滤。我让用户填写一个表格,其中所有字段都是可选的。如果用户没有指定他要查找的尺寸,则@enrollment变量不会被定义。在这种情况下,我不希望查询查询大小。我怎么能这样做?

1 个答案:

答案 0 :(得分:3)

@colleges = College.where(category: @university_type)
@colleges = @colleges.where("us_news_ranking <= ?", @rank) unless @rank.blank?
@colleges = @colleges.where("size <= ?", @enrollment) unless @enrollment.blank?