Delete model objects with association links

❮ Back Next ❯

In this step, you will learn some different ways to delete model objects and their association links with other objects.

The Rails console should still be running from the previous step.

Delete an object from a has_many collection

In this part, we will delete a departure Flight object from the has_many collection of an Airport object.

Retrieve the MEM Airport object by invoking the Airport.find_by method in the console:

mem = Airport.find_by(airport_code: 'MEM')

Pretty print the mem object’s departure_flights collection of associated Flight objects:

mem.departure_flights

Note that the collection contains two Flight objects with id 1 and id 2, respectively.

Retrieve the first Flight object with id 1 from the mem object’s departure_flights collection:

flight_1 = mem.departure_flights.find(1)

Delete the Flight object flight_1, removing it from the mem object’s departure_flights collection:

mem.departure_flights.destroy(flight_1)

Note that the call to destroy results in a SQL DELETE command being run, indicating that the Flight object was deleted from the database.

Pretty print the mem object’s departure_flights collection of associated Flight objects:

mem.departure_flights

Note that Flight object with id of 1 has now been deleted from the collection.

Delete an object along with all the dependent objects it its has_many collection

In this part, we will delete the Airport object lax along with all of the Flight objects in its departure_flights collection.

Pretty print the lax object’s departure_flights collection:

lax.departure_flights

Note that lax has two Flight objects in its collection

Delete the Airport object lax by calling its destroy method:

lax.destroy

Note that three SQL DELETE commands resulted from this call to destroy. The first two DELETE commands deleted the two Flight objects in the lax object’s departure_flights collection. The third DELETE command deleted the lax object itself. The reason that the Flight objects were automatically deleted was because of the dependent: destroy argument that we included in the has_many declaration in the Flight class.

Exit the Rails console:

exit

❮ Back Next ❯