2011-01-06 32 views
0

我正在拼車應用程序中,人們可以搜索電梯。他們應該能夠選擇他們希望從中選擇的城市,並選擇一個半徑,然後將範圍內的城市添加到查詢中。然而,目前爲止,我只能將一堆"AND"條件鏈接在一起,在那裏它可以說"WHERE start_city = city_from OR start_city = a_city_in_range OR start_city = another_city_in_range"Rails 3中的動態「OR」條件

有沒有人知道如何實現這個?首先十分感謝。

class Search < ActiveRecord::Base 

def find_lifts  
    scope = Lift.where('city_from_id = ?', self.city_from) 
    #returns id of cities which are in range of given radius 
    @cities_in_range_from = City.location_ids_in_range(self.city_from, self.radius_from) 
    #adds where condition based on cities in range 
    for city in @cities_in_range_from 
    scope = scope.where('city_from_id = ?', city) 
    #something like scope.or('city_from_id = ?', city) would be nice..   
    end 
end 
+0

慣於這種搜索管芯的多次並行請求時,你去住嗎?考慮到你在每一行有10-12個參數的線性搜索?管理複雜的數據庫暨Web服務器拓撲將成爲系統管理員的噩夢。 – Siddharth 2012-07-02 18:52:17

回答

2

你可以用「IN」操盤手「=」,而無需使用SQL語法 隨着阿雷爾(由Rails的3.0中使用),你可以做這樣

class Search < ActiveRecord::Base 

    def find_lifts  

    #returns id of cities which are in range of given radius 
    @cities_in_range_from = City.location_ids_in_range(self.city_from, self.radius_from) 
    scope = Lift.where{ :city_from_id => [self.city_from] + @cities_in_range_from }) 

    # ... and so on 
    end 
end 
+0

像一個迷人的作品。謝謝! – 2011-01-06 15:22:41