Order an array. undefined `order 'method for an array. Convert array to hash?

I have a city model and in a show in the city I want to display hotels near specific places in the city. Cities have several places; Hotels are searched using a geocoder next to the method.

To add an order function, I followed Ryan Bates screencasts # 228 , but this approach does not seem to work with arrays giving the error undefined method `order' for #< Array:0x007f960d003430>

 cities_controller.rb helper_method :sort_column, :sort_direction def show session[:search_radius] = 2 if session[:search_radius].blank? @city = City.find(params[:id]) @locations = @city.locations @hotels = [] @locations.each do |location| unless location.longitude.blank? || location.latitude.blank? center_point = [location.latitude, location.longitude] box = Geocoder::Calculations.bounding_box(center_point, session[:search_radius]) thotels = Hotel.near(center_point, session[:search_radius]).within_bounding_box(box) else thotels = Hotel.near(center_point, session[:search_radius]) end @hotels += thotels if thotels @hotels = @hotels.uniq end @hotels = @hotels.order(sort_column + " " + sort_direction).paginate(:page => params[:page], :per_page => 5) @json = @locations.to_gmaps4rails respond_with @json, :location => city_url end private def sort_column Hotel.column_names.include?(params[:sort]) ? params[:sort] : "name" end def sort_direction %w[asc desc].include?(params[:direction]) ? params[:direction] : "asc" end 

My question is: should I concentrate on converting the array to a hash, or should I first create a hotel hash, or maybe find a completely different approach for sorting?

+4
source share
1 answer

order is the method used for sorting at the database level. since @hotels is an array, you cannot sort with order . Try the following (not verified, and you might want to enable pagination if you haven't already enabled it)

 @hotels = @hotels.sort_by(&:"#{sort_column}") @hotels = @hotels.reverse if sort_direction == 'DESC' @hotels = @hotels.paginate(:page => params[:page], :per_page => 5) 
+9
source

All Articles