Search code examples
ruby-on-railsruby-on-rails-3activerecordcallbackafter-create

after_create destroy a record


I have two tables bookings and rentals. A user books a car to rent and an admin approves the rental.

As the admin approves the rental. The booking is no longer needed. How can i delete the booking record at the same time as creating the rental record.

this was my attempt (i'm new to ruby so apolagies if i am being stupid)

#rental_controller.rb
after_create :delete_booking

def delete_booking
  @booking = Booking.find(params[:id])
  @booking.destroy

respond_to do |format|
  format.html { redirect_to rental_url }
  format.json { head :no_content }
end
end

Solution

  • After create belong in the model, not the controller. I'm assuming you have a rental model since the snippet is from the rentals controller.

    In the rental model:

    after_create :delete_booking
    
    
    def delete_booking
      @booking = Booking.where(:booking_no => self.booking_no).first
      @booking.destroy
    end