Im trying to create a new alert only if is covered returns true, how can I access the object from new to check if it is covered or not, and if it is save correctly if not respond with the errors. My error is NameError (undefined local variable or method `params' for #):
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
Controller
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