Mar*_*als 0 ruby ruby-on-rails
我是新手,我想知道是否可以用params定义模型方法.我的意思是.我有这种方法用球坐标计算距离
#in my model
#Haversin formula to calculate distance between spherical coordinates
def self.distance(b)
rad_per_deg = Math::PI/180 # PI / 180
rkm = 6371 # Earth radius in kilometers
#rm = rkm * 1000 # Radius in meters
a=[]
a.push(self.lat)
a.spuh(self.long)
dlon_rad = (b[1]-a[1]) * rad_per_deg # Delta, converted to rad
dlat_rad = (b[0]-a[0]) * rad_per_deg
lat1_rad, lon1_rad = a.map! {|i| i * rad_per_deg }
lat2_rad, lon2_rad = b.map! {|i| i * rad_per_deg }
a = Math.sin(dlat_rad/2)**2 + Math.cos(lat1_rad) * Math.cos(lat2_rad) * Math.sin(dlon_rad/2)**2
c = 2 * Math.asin(Math.sqrt(a))
distance=rkm * c
return distance
end
Run Code Online (Sandbox Code Playgroud)
我希望它的工作方式如下:obj.distance(b)其中b是纬度和经度的数组.但是当我在irb上尝试这个时,我得到:
NoMethodError: undefined method `distance' for #<Object:0x000000058854c8>
Run Code Online (Sandbox Code Playgroud)
可能我错过了一些东西.
class Meteo < ActiveRecord::Base
attr_accessible :date, :humidity, :lat, :long, :pressure, :temp, :town, :wind, :wind_direction
, :rain_quantity
#Haversin formula to calculate distance between spheric coordinates
def self.distance(b)
rad_per_deg = Math::PI/180 # PI / 180
rkm = 6371 # Earth radius in kilometers
#rm = rkm * 1000 # Radius in meters
a=[]
a.push(self.lat)
a.spuh(self.long)
dlon_rad = (b[1]-a[1]) * rad_per_deg # Delta, converted to rad
dlat_rad = (b[0]-a[0]) * rad_per_deg
lat1_rad, lon1_rad = a.map! {|i| i * rad_per_deg }
lat2_rad, lon2_rad = b.map! {|i| i * rad_per_deg }
a = Math.sin(dlat_rad/2)**2 + Math.cos(lat1_rad) * Math.cos(lat2_rad) * Math.sin(dlon_rad/2)
**2
c = 2 * Math.asin(Math.sqrt(a))
distance=rkm * c
return distance
end
end
Run Code Online (Sandbox Code Playgroud)
我在irb上称之为:
irb> m = Meteo.last
irb> b = [86.43971008189519,23.477053751481986]
irb> m.distance(b)
小智 5
只需删除self.
编写时def self.distance,意味着将在模型类上调用该方法.def distance如果希望在模型实例上调用方法,则应该使用.
相比:
class SomeModel
def self.distance
# ...
end
end
SomeModel.distance
Run Code Online (Sandbox Code Playgroud)
附:
class SomeModel
def distance
# ...
end
end
obj = SomeModel.new
obj.distance
Run Code Online (Sandbox Code Playgroud)