Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

ruby on rails - Order array. undefined method `order' for Array. Convert array into hash?

I have a City model and in city's show action I want to render hotels nearby specific locations in the city. Cities has_many locations; hotels are being searched using Geocoder near method.

To add order functionality I've followed Ryan Bates screencasts #228, but this approach doesn't seem to work with arrays, giving 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 in converting an array into hash or should I initially create hash of hotels, or maybe find completely different approach to perform sorting?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

order is a method used for sorting at the database level. since @hotels is an array, you won't be able to sort using order. Try the following (not tested and you may want to include array pagination if you haven't included it yet)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...