我是新手,我想知道是否可以用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
我希望它的工作方式如下:obj.distance(b)其中b是纬度和经度数组。但是当我在irb上尝试这个时,我得到了:
NoMethodError: undefined method `distance' for #<Object:0x000000058854c8>
可能我错过了一些东西。
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
我在irb上称之为:
IRB&GT;米= Meteo.last
IRB&GT; b = [86.43971008189519,23.477053751481986]
IRB&GT; m.distance(b)中
答案 0 :(得分:5)
只需删除self
。
当您编写def self.distance
时,您的意思是将在模型类上调用该方法。如果希望在模型实例上调用方法,则应使用def distance
。
比较
class SomeModel
def self.distance
# ...
end
end
SomeModel.distance
使用:
class SomeModel
def distance
# ...
end
end
obj = SomeModel.new
obj.distance
答案 1 :(得分:2)
如果我说得对,你正在定义一个类方法(使用def self.distance
),但是在该类的实例(obj.distance(array)
)上调用它。
您应该在obj的类上调用该方法,例如Meteo.distance(array)
。
或者只需将self
保留在方法定义中即可将其定义为实例方法。
希望,这有帮助