Question

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
Was it helpful?

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

OTHER TIPS

Ideally something like ..

# Booking.rb Model

has_one :booking

And

# Rental.rb Model

belongs_to :booking, :class_name => "Booking", :foreign_key => "booking_no"

after_create :delete_booking

private
  def delete_booking
    self.booking.destroy
  end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top