0
我试图创建一个新的警报只有当覆盖返回true,我如何从新访问该对象以检查它是否被覆盖,如果它是正确保存if没有回应的错误。我的错误是NameError(未定义的局部变量或方法`PARAMS'为#):如何验证之前保存与对象从新的行动
class Alert < ActiveRecord::Base
belongs_to :user
has_many :activities
scope :by_year, lambda { |year| where('extract(year from created_at) = ?', year) }
validate :is_covered, :before => :create
def is_covered
@schools = School.all
@schools.each do |school|
distance = triangulate(school.latitude, school.longitude, self.latitude, self.longitude)
if distance < school.radius.to_f
self.school_id = school.id
return self
else
self.errors.add(:latitude,"Sorry You Arent Within a School")
return self
end
end
end
def power(num, pow)
num ** pow
end
def triangulate(lat1, lng1, lat2, lng2)
dtor = Math::PI/180
r = 6378.14*1000
rlat1 = lat1.to_f * dtor
rlong1 = lng1.to_f * dtor
rlat2 = lat2.to_f * dtor
rlong2 = lng2.to_f * dtor
dlon = rlong1 - rlong2
dlat = rlat1 - rlat2
a = power(Math::sin(dlat/2), 2) + Math::cos(rlat1) * Math::cos(rlat2) * power(Math::sin(dlon/2), 2)
c = 2 * Math::atan2(Math::sqrt(a), Math::sqrt(1-a))
distance = r * c
return distance
end
end
控制器
def create
@alert = Alert.create(alert_params).is_covered
@alert.status = "active"
respond_to do |format|
if @alert.save && @alert.valid?
log_activity(nil, "has created alert", @alert.id, @alert.school_id, "Alert")
format.json { render json: @alert.id}
else
format.json { render json: @alert.errors, status: :unprocessable_entity }
end
end
end
如果我确实使用了,我该如何获得警报对象 – user3882976
我应该使用自我 – user3882976
是的,你可以在方法中使用self。但是你可以排除自我。例如:如果您想要活动,您可以调用self.activities,这与调用活动相同。 – neo