Update existing association links

❮ Back Next ❯

In this step, we will change the departure airport for the most recently created Flight object (the one with id of 6). To accomplish this task, we will update its association link to connect it to the ATL airport instead of LAX.

Retrieve the Flight object with id of 6 by invoking the find method on the lax object’s departure_flights:

atl_mem = lax.departure_flights.find(6)

Retrieve the ATL Airport object by invoking the Airport.find_by method:

atl = Airport.find_by(airport_code: 'ATL')

Pretty print theAirport object atl:

atl

Note that atl has an id of 2.

Update the atl_mem object’s departure_airport to be atl:

atl_mem.departure_airport = atl

Note that no SQL commands were included in the output, indicating that no change was saved to the database.

Pretty print the Flight object atl_mem:

atl_mem

Note that the atl_mem object’s departure_airport_id has been updated to 2, the id of the atl object.

Save the changes made to the Flight object atl_mem to the database:

atl_mem.save

Note that invoking the save method resulted in a SQL UPDATE command being run, indicating that the updates made to the object were saved to the database.

To confirm the update, pretty print departure_flights for the Airport object atl:

atl.departure_flights

Note that the Flight object with id of 6 has now been added to the atl object’s departure_flights collection.

You will notice something confusing if you pretty print the lax object’s departure_flights collection:

lax.departure_flights

Note that the Flight object with id of 6 still appears in the collection. The reason for this discrepancy is that, even though the database was updated correctly, the local copies of the objects were not all updated.

To refresh the lax object and its departure_flights collection, call the reload method:

lax.reload

Note that a SQL SELECT command was run, indicating that the latest data from the database was retrieved.

Pretty print the lax object’s departure_flights collection:

lax.departure_flights

Note that the collection now appears as expected, with the Flight object with id of 6 no longer present.

Keep the console running, as we will continue to use it in the next step.


❮ Back Next ❯