Dynamic "OR" conditions in Rails 3
I am working on a carpool application where people can search for lifts. They should be able to select the city from which they would liked to be picked up and choose a radius which will then add the cities in range to the query. However the way it is s开发者_StackOverflow中文版o far is that i can only chain a bunch of "AND"
conditions together where it would be right to say "WHERE start_city = city_from OR start_city = a_city_in_range OR start_city = another_city_in_range"
Does anyone know how to achive this? Thanks very much in advance.
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
You can use "IN" operator instead of "=" without using SQL syntax With Arel (used by Rails 3.0) you can do that this way
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
精彩评论