Rails: renaming a controller and corresponding model

前端 未结 5 885
南笙
南笙 2021-01-21 07:27

Is there an easy way to rename a controller and model in my app and all the instances in the corresponding code?

I\'m using textmate, would this be as simple as using t

相关标签:
5条回答
  • 2021-01-21 07:54

    To rename controller and model use this gem https://github.com/jcrisp/rails_refactor

    0 讨论(0)
  • 2021-01-21 07:55

    Yes and no. You can rename it that way, but you'll also need to rename the files as well or Rails won't know where to look for the files corresponding to the new Report model/controller/etc.

    0 讨论(0)
  • 2021-01-21 07:57

    You need to change the name of the Controller and the associated Model, Views, Helpers, Tests & Routes directories, file names, class names & the names in the class definitions.

    I found two ways to do this but before you try anything I recommend you back-up your app, preferably with a Software Version Control system like Git & Github.com.

    Your first option is to do it manually & there is a good explanation on how to do this here: How to rename rails controller and model in a project

    Another way is to destroy your controller & model, and then generate a new one, this will remove all the files which were generated the first time round & replace them with new ones. Michael Hartl explains this solution well in his online guide to Ruby on Rails here: http://ruby.railstutorial.org/chapters/static-pages#sidebar-undoing_things

    This is the solution I followed when I needed to make this change to my app, I needed to replace a MVC scaffold I generated called board with a new one called product.

    1. First

    I made a back-up of the work I did in the layout of the board view, app/views/boards/index.html.erb

    2. Then

    I ran the below rails commands in the terminal window.

    $ rake db:rollback
    
    $ rails destroy scaffold board name:string description:text image:string price:decimal
    
    $ rails generate scaffold product product_type:string name:string description:text image:string price:decimal
    
    $ rake db:migrate
    

    3. Finally

    I copied my backed-up boards/index.html.erb file into the newly generated app/views/products/index.html.erb & did a find & replace in my text editor on this file to replace board with product.

    I think the second option is much more reliable & quicker but it’s important to make this change early on in your project before you make too many manual changes to the code. It would be better to just take a little more time planning your MVC names & database tables properly before you start your project.

    0 讨论(0)
  • 2021-01-21 08:01

    If you are using textmate, use 'command-shift-f" to look for a string throughout your entire project.

    0 讨论(0)
  • 2021-01-21 08:11

    You can also use rails_refactor gem to rename controller, model, etc for more info check https://github.com/jcrisp/rails_refactor

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