Search code examples
elixirphoenix-framework

How to generate or remove single field after I've already used generator in Phoenix


I used the phx.gen.html generator to create a table and related controller and view data using this command:

mix phx.gen.html TestBeds TestBed testbeds name:string version:string note:string developer:string status:string status_action_value:string

I then wrote code based on the generated table. In retrospect I need another field that populates across the codebase including the form field the generator made.

I want to add an additional field using the generator so that I don’t need to manually update each code piece throughout the codebase. How do I do that?

Also, if I want to remove a field using the generator, how can I do that?

Thank you.


Solution

  • Generators themselves are basically one-way doors. But assuming you use a version control system like git, and assuming the inadequate change has not already been deployed or merged, you can follow a procedure something like this:

    1. run mix.ecto.rollback
    2. Git commit your changes "so far" in a branch, or at least stage them with git add .
    3. Run the generator with the added/removed fields
    4. Because the dates will be different on your migration, you'll end up with another migration file. Pick a winner. Delete the one you don't need, which will probably be the older one.
    5. Re-run the migration with the change. You'll get two warnings in interactive prompts, the first asking if you really mean to add things to an existing context (answer Y), and the second asking if you want to do an "interactive overwrite." Answer Y.
    6. Unchanged files will not prompt you for anything. But for each generated file that differs from what is being generated, you'll be prompted whether you want to do the overwrite. You can choose "Y" unless you happen to know you made significant enough code edits there that you'd be better off making the change manually.
    7. Reconcile the changes against what you already have with the help of git diff or a similar tool.

    If you've already merged/deployed changes, the procedure I'd follow would be to create a new change migration (you can use the ecto generator for that if you like), and manually update the schema, view(s), and changeset functions.

    In practice, a change like this is almost certainly going to require changes to your model module, your test fixtures, views, and probably your controller and re-running the generator doesn't buy you much, so I usually just do this sort of change by hand. It's also unusual when the scaffolded views are similar enough to what I would actually consider deploying that the generator saves me much time. In my own team, a few people end up not using the generators at all.