Here, we are going to create a situation where we can see what new methods are created in Rails, when a new field is added to a table.
To accomplish this, we can use two consoles. One will be a simple command line, and the other will be a rails console.
In the first console, it’s important to stay logged in; we’re going to capture the list of methods on the ‘enemy’ table, before and after a migration, so that we can easily see the difference, and run a migration in the second console, to actually add a field to the database.
In the first console (a rails console), run the following command:
enemy_methods_before_migration = Enemy.first.methods ; nil
In the second console, not a rails console, run these commands:
rails g migration addNameToEnemy name:string
rails db:migrate
Then, going back to the first console, we are going to reload all of our Rails classes, in order to get these changes, get the new list of methods, and compare them to the previous list.
reload!
enemy_methods_after_migration = Enemy.first.methods ; nil
enemy_methods_after_migration - enemy_methods_before_migration
This reveals all of the methods that are created, just based on adding a field to a database table!
[:name_was, :name_previously_changed?, :name_previous_change, :restore_name!, :saved_change_to_name?, :saved_change_to_name, :name_before_last_save, :will_save_change_to_name?, :name_change_to_be_saved, :name_in_database, :name, :name=, :name_before_type_cast, :name_came_from_user?, :name?, :name_changed?, :name_change, :name_will_change!]
running this command:
(enemy_methods_after_migration - enemy_methods_before_migration).count
reveals that 18 methods were created. Their names reveal a little bit about the functionality we now have access to, for that field.