How to rename rails controller and model in a project

后端 未结 8 1021
遥遥无期
遥遥无期 2020-11-29 17:39

I started a Rails app and everything works fine. But now, I would like to rename a controller and the associated model:

I wanted to change the Corps con

相关标签:
8条回答
  • 2020-11-29 18:12

    As someone that just finish this painful process the MOST important step is to build enough TESTS to check as much functionality as possible. They should cover not only the model/controller that you plan to rename but also all other models/controllers/views parts. Anyhow it's a good (or maybe even a must) practice.

    Do this steps by iterations, sometimes you need to comeback to steps few times (5 and more) to discover additional files that need to be changed. And now for the rename steps:

    1. Change all the files (name and content) the include Corps/Corp to Stores/Store in db/migrate folder
    2. Try to run:

      rake db:drop:all

      rake db:create

      rake db:migrate

    3. Change content of db/seeds.rb file.

    4. Try to run: rake db:seed --trace (In this step you may need to change some other model/controller files.)
    5. Change test/fixtures files. you may need to change not only corps.yml but other related files (some files may include corp_id).
    6. Try to run your tests, it's better to run it with fixed seed (add: TESTOPTS="--seed=1981" or any other number)
    7. Rename to files (name and content) be carefull sometimes you need to change test and other app file
    0 讨论(0)
  • 2020-11-29 18:15

    One other important thing is that you need to update the model associations, which you'll have to do whether you rename manually or destroy and generate the resource (since they exist in the other models). You can either run a migration to change the column names of the foreign keys in the database and change all references to those foreign keys in the code:

    rename_column :table, :old_id, :new_id
    

    or set a custom foreign key when declaring the association that uses the old foreign key:

    belongs_to :new, foreign_key: "old_id"
    

    Also if your resource includes images, they are often stored in a directory that includes the resource name but (with carrierwave at least) once the resource's name is changed they'll be referenced incorrectly (file exists at '/uploads/old/image/1/pic.jpg' but is looked for at 'uploads/new/...'), so you'll have to either delete and re-upload the images, move them to the new path, or perhaps change where they're being looked for.

    0 讨论(0)
提交回复
热议问题