为了数组。未定义的方法`秩序“的阵列。转换数组哈希? [英] Order array. undefined method `order' for Array. Convert array into hash?

查看:87
本文介绍了为了数组。未定义的方法`秩序“的阵列。转换数组哈希?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个城市模型,并在城市的演出行动我想呈现的酒店在城市附近的特定位置。城市HAS_MANY地点;使用方法附近的地理codeR正在搜索的酒店。

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.

要增加订单功能,我跟着瑞恩·贝茨截屏#228 ,但这种做法似乎并不使用数组的工作,给错误未定义的方法`秩序为#<阵列:0x007f960d003430>

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?

推荐答案

订单是用于在数据库级别排序的方法。因为 @hotels 是一个数组,你将无法使用订单进行排序。请尝试以下方法(未测试,你可能要包括数组分页,如果您还没有它尚未)

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)

这篇关于为了数组。未定义的方法`秩序“的阵列。转换数组哈希?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆