0

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
Messyeater
  • 117
  • 1
  • 11
  • It looks like you ar trying to do too much in one method and breaking mvc. Is the snippet from your model? If so, the respond_to belongs in the controller not the model. Maybe try rephrasing your question because I don't quite understand what you are trying to do. – John Dec 10 '12 at 00:49
  • @John i have tried my best to re-phrase the question. It's quite hard to work – Messyeater Dec 10 '12 at 00:59
  • I added an answer of what I think is wrong. What is the relationship between rental and booking (has_many, belongs_to, has_one, none)? – John Dec 10 '12 at 01:06

2 Answers2

1

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
John
  • 4,362
  • 5
  • 32
  • 50
  • booking_no is the relationship between booking and rental – Messyeater Dec 10 '12 at 01:07
  • Rental and Booking have a column called booking_no? Updated my answer. Let me know if that works for you. – John Dec 10 '12 at 01:11
  • 1
    Note that you probably don't want to *delete* the booking, just mark it completed. It's pretty rare in real-world applications that you want to completely remove a record as though it never existed. If there's a problem with somebody's rental, suddenly it's their word against yours that they had booked it on such-and-such a day for such-and-such a model of car. – user229044 Dec 10 '12 at 05:16
0

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
James
  • 2,284
  • 1
  • 20
  • 29