ich*_*kov 8 arrays hash ruby-on-rails ruby-on-rails-3
我有一个城市模型,在城市的展示活动中,我想要在城市中的特定位置附近的酒店.城市有很多地方; 酒店正在使用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
Run Code Online (Sandbox Code Playgroud)
我的问题是:我应该专注于将数组转换为哈希值,还是应该最初创建酒店哈希值,还是找到完全不同的方法来执行排序?
jvn*_*ill 13
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)
Run Code Online (Sandbox Code Playgroud)