Reputation: 629
I tried to write down a before_destroy callback, which should let users cancel a booking at least 2 hours before the departure time.
Here's what I wrote so far
app/model/reservation
class Reservation < ActiveRecord::Base
before_destroy :verify
private
def verify
if !(:ensure_deletable)
record.errors[:base] << 'error'
end
end
def ensure_deletable
if self.date_trip.to_time < Time.now + 2
return true
end
end
end
This code gives me no error but it does let a user cancel a booking in any time..
Can you help me? thanks
EDIT:
thank to your answers I modified the code as here below.
class Reservation < ActiveRecord::Base
before_destroy :verify
belongs_to :dep ,:class_name => 'Stop', :foreign_key => 'dep_id'
belongs_to :arr ,:class_name => 'Stop',:foreign_key => 'arr_id'
belongs_to :route
belongs_to :user
delegate :CountStop, :to => :route, prefix: true, :allow_nil => false
delegate :city ,:to => :arr, :allow_nil => false
delegate :city ,:to => :dep, :allow_nil => false
def verify
if ensure_deletable
false
end
end
private
def ensure_deletable
if self.date_trip.to_time < Time.now + 2
return true
end
end
end
In this way I can cancel only the reservations that has at least two hours before the departure. Is this correct?
Upvotes: 1
Views: 106
Reputation: 50057
Why not just do
class Reservation < ActiveRecord::Base
before_destroy :ensure_deletable
private
def ensure_deletable
# can be deleted up to two hours before time
deletable = Time.now + 2.hours < self.date_trip.to_time
record.errors << 'Reservation can no longer be deleted' unless deletable
deletable
end
end
Upvotes: 2
Reputation: 10406
Validation only occurs when saving or updating and object, it doesn't prevent them being deletable. According to APIdock simply returning false from your before_destroy
will stop the action from being done.
So try:
def verify
if !ensure_deletable
false
end
end
Upvotes: 2
Reputation: 114138
if !(:ensure_deletable)
doesn't invoke your ensure_deletable
method. It checks if the symbol :ensure_deletable
is nil
or false
. This will of course always return false
.
To invoke your method, you have to write:
if !ensure_deletable
# ...
end
or
unless ensure_deletable
# ...
end
Furthermore, you probably have to return false
from your callback as noted by japed.
Upvotes: 2