2012-07-01 66 views
1

我有這個疑問:這ActiveRecord的查詢返回意外的結果,如何解決

@listings = Listing.where('city != ?', 'SommerVille') 

我想知道如果任何人有其他什麼可能導致這有什麼建議?

我只想從那裏的城市!= SommerVille獲得那些房源。

感謝


編輯 上述問題是由於領導或城市名尾隨空格。 所以我想知道什麼是最好的方式來查詢數據庫,它忽略了大小寫,也忽略了前導/尾隨空格。

下面的方法工作,但有沒有更好的辦法?

@unwanted_cities = Listing.where(['city != ?', "SommerVille"]).where(['city != ?', " SommerVille"]).where(['city != ?', "SommerVille "]) 

回答

0

我想大多數DBS支持修剪

@listings = Listing.where('TRIM(city) != ?', 'SommerVille') 

這將是從長遠來看更好地剝離的方式空白到你的數據庫忽略大小寫

的一種方式,使用上

@listings = Listing.where('UPPER(TRIM(city)) != UPPER(?)', 'SommerVille') 

或者

@listings = Listing.where('UPPER(TRIM(city)) != ?', 'SommerVille'.upcase)