I am fairly new to ROR and am working on a cargo tracking project. The idea is to log all changes to shipment location so that when users track their shipment with a tracking number they would see the current location and a history of locations passed.
I have a shipments table and a shipment_locations table.
Shipments
+--------------------------+--------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +--------------------------+--------------+------+-----+---------+----------------+ | id | int(11) | NO | PRI | NULL | auto_increment | | start_address_id | int(11) | YES | | NULL | | | end_address_id | int(11) | YES | | NULL | | | transportation_agency_id | int(11) | YES | MUL | NULL | | | customer_id | int(11) | NO | MUL | NULL | | | status_id | int(11) | NO | MUL | NULL | | | cargo_id | int(11) | YES | MUL | NULL | | | tracking_number | varchar(255) | NO | MUL | NULL | | | mode_of_transport_id | int(11) | YES | MUL | NULL | | | expected_start_date | date | YES | | NULL | | | actual_start_date | date | YES | | NULL | | | expected_end_date | date | YES | | NULL | | | actual_end_date | date | YES | | NULL | | | created_at | datetime | NO | | NULL | | | updated_at | datetime | NO | | NULL | | | admin_user_id | int(11) | YES | MUL | NULL | | +--------------------------+--------------+------+-----+---------+----------------+
shipment_locations: (Location updates are done on this table, under (current_location))
+------------------+--------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +------------------+--------------+------+-----+---------+----------------+ | id | int(11) | NO | PRI | NULL | auto_increment | | shipment_id | int(11) | NO | MUL | NULL | | | current_location | varchar(255) | YES | | NULL | | | final_location | text | YES | | NULL | | | created_at | datetime | NO | | NULL | | | updated_at | datetime | NO | | NULL | | +------------------+--------------+------+-----+---------+----------------+
Shipment_history (proposed)
Fields:
- id
- shipment_id
- current_location
- created_at
- updated_at
I would like to store all the updates from shipment_locations table to this history table so that users can get:
Time (Updated_at):----------------------------> Location:(current_location)
1/12/2012 11:30 222 John st.
1/12/2012 13:00 555 Paul st.
1/13/2012 07:30 final_location
How can this be achieved from the controllers so that only one update action saves to history table?
UPDATE:
I was able to get a shipment tracking log using this trigger, thanks vladr
DELIMITER $$
DROP TRIGGER shipment_after_update
$$
CREATE TRIGGER shipment_after_update
AFTER UPDATE on shipments
FOR EACH ROW
BEGIN
INSERT INTO cargo_transit_histories
(shipment_id
, current_location
, final_location
, updated_at
)
VALUES
(NEW.id, NEW.current_location, NEW.final_location, NOW());
END$$
DELIMITER ;