8

私は都市モデルを持っており、都市のショーアクションで、都市の特定の場所の近くにあるホテルをレンダリングしたいと考えています。都市には多くの場所があります。ホテルはGeocoder Nearメソッドを使用して検索されています。

注文機能を追加するために、Ryan Batesスクリーンキャスト #228に従いましたが、このアプローチは配列では機能しないようで、エラーが発生します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

私の質問は次のとおりです。配列をハッシュに変換することに集中する必要がありますか、最初にホテルのハッシュを作成する必要がありますか、それともソートを実行するためのまったく異なるアプローチを見つける必要がありますか?

4

1 に答える 1

15

orderデータベース レベルでの並べ替えに使用される方法です。は配列であるため@hotels、 を使用してソートすることはできませんorder。以下を試してください (まだテストされていないため、配列のページネーションをまだ含めていない場合は含めることができます)。

@hotels = @hotels.sort_by(&:"#{sort_column}")
@hotels = @hotels.reverse if sort_direction == 'DESC'
@hotels = @hotels.paginate(:page => params[:page], :per_page => 5)
于 2013-03-31T16:11:56.393 に答える