我在数据库中定义一个搜索以返回一些行。然后我在控制器中计算距离。我希望能够像其他列一样在我的视图中引用计算的距离(d)。我该怎么做?
这是我将计算推入模型的尝试:
在欢迎控制器中:
def search
@coordinates = Geocoder.coordinates(params[:address])
lat = res[:latitude].to_f
long = res[:longitude].to_f
@places = Place.within_miles_of(lat: lat, long: long)
end
在places模型中:
class Place < ActiveRecord::Base
validates :user_id, presence: true
#belongs_to :user
validates_presence_of :title, :address, :postcode, :category, :phone
geocoded_by :postcode
after_validation :geocode, :if => :postcode_changed?
belongs_to :user
def self.within_miles_of(coords = {})
ids = []
Place.select("id,latitude,longitude").where("category='#{params[:category]}'").each do |res|
lat = res[:latitude].to_f
long = res[:longitude].to_f
d = Geocoder::Calculations.distance_between(@coordinates,[lat,long])
puts d
ids << res[:id] if d <= 5
end
if ids.any?
@places = Place.where("id in #{ids}".gsub("[","(").gsub("]",")")).paginate(:page => params[:page], :per_page => 9)
else
@places = []
end
end
end
我似乎收到以下错误:
未定义的局部变量或方法`res'
答案 0 :(得分:1)
您可以向模型添加一个类方法,该方法采用您需要的任何参数并返回计算值。
def self.within_miles_of(coords = {})
# Calculate here
end
答案 1 :(得分:0)
课程方法
您最好在class vs instance methods上阅读 - 基本上您尝试添加到model
是class method
来提取所需数据:
#app/models/place.rb
class Place < ActiveRecord::Base
def self.within_miles_of(category, page = 1)
ids = []
Place.select("id,latitude,longitude").where(category: category).each do |res|
lat = res[:latitude].to_f
long = res[:longitude].to_f
d = Geocoder::Calculations.distance_between(@coordinates,[lat,long])
puts d
ids << res[:id] if d <= 5
end
@places = ids.any? ? Place.where("id in #{ids}".gsub("[","(").gsub("]",")")).paginate(:page => page, :per_page => 9) : @places = []
end
end
#app/controllers/your_controller.rb
Class Controller < ApplicationController
# ...
@places = Place.within_miles_of(category)
end
-
<强>修正强>
您的主要问题是您是否正试图致电category = #{params["category"]}
。模型中没有params
;所以你也必须通过arguments
中的类别(同样适用于pages
param)
说实话,我认为您的代码可能会被大量干扰