如何编写迁移来重命名 Rails 中的 ActiveRecord 模型及其表?

发布于 2024-07-12 04:34:37 字数 71 浏览 5 评论 0原文

我不擅长命名,并意识到我的 Rails 应用程序中有一组更好的模型名称。
有没有办法使用迁移来重命名模型及其对应的表?

I'm terrible at naming and realize that there are a better set of names for my models in my Rails app.
Is there any way to use a migration to rename a model and its corresponding table?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

自由如风 2024-07-19 04:34:37

这是一个示例:

class RenameOldTableToNewTable < ActiveRecord::Migration
  def self.up
    rename_table :old_table_name, :new_table_name
  end

  def self.down
    rename_table :new_table_name, :old_table_name
  end
end

我必须手动重命名模型声明文件。

编辑:

在 Rails 3.1 & 中 4、ActiveRecord::Migration::CommandRecorder 知道如何反转 rename_table 迁移,因此您可以执行以下操作:(

class RenameOldTableToNewTable < ActiveRecord::Migration
  def change
    rename_table :old_table_name, :new_table_name
  end 
end

您仍然需要手动重命名文件。)

Here's an example:

class RenameOldTableToNewTable < ActiveRecord::Migration
  def self.up
    rename_table :old_table_name, :new_table_name
  end

  def self.down
    rename_table :new_table_name, :old_table_name
  end
end

I had to go and rename the model declaration file manually.

Edit:

In Rails 3.1 & 4, ActiveRecord::Migration::CommandRecorder knows how to reverse rename_table migrations, so you can do this:

class RenameOldTableToNewTable < ActiveRecord::Migration
  def change
    rename_table :old_table_name, :new_table_name
  end 
end

(You still have to go through and manually rename your files.)

那一片橙海, 2024-07-19 04:34:37

在 Rails 4 中,我所要做的就是 def 更改,

def change
  rename_table :old_table_name, :new_table_name
end

并且我的所有索引都为我处理好了。 我不需要通过删除旧索引并添加新索引来手动更新索引。

它也可以利用指数上升或下降的变化。

In Rails 4 all I had to do was the def change

def change
  rename_table :old_table_name, :new_table_name
end

And all of my indexes were taken care of for me. I did not need to manually update the indexes by removing the old ones and adding new ones.

And it works using the change for going up or down in regards to the indexes as well.

剪不断理还乱 2024-07-19 04:34:37

其他答案和评论涵盖了表重命名、文件重命名和 grep 代码。

我想补充一些注意事项:

让我们使用我今天遇到的一个现实示例:将模型从“Merchant”重命名为“Business”。

  • 不要忘记更改依赖表和模型的名称
    相同的迁移。 我同时将 Merchant 和 MerchantStat 模型更改为 Business 和 BusinessStat。 否则,在执行搜索和替换时,我将不得不进行太多的挑选和选择。
  • 对于通过外键依赖于您的模型的任何其他模型,其他表的外键列名称将从您的原始模型名称派生。 因此,您还需要对这些依赖模型进行一些 rename_column 调用。 例如,我必须在各种连接表(对于 has_and_belongs_to_many 关系)和其他依赖表(对于正常的 has_one 和 has_many 关系)中将“merchant_id”列重命名为“business_id”。 否则我最终会得到像“business_stat.merchant_id”这样的列指向“business.id”。 这是关于进行列重命名的一个很好的答案。< /a>
  • grep 时,记得搜索单数、复数、大写、
    小写,甚至大写(可能出现在注释中)版本
    你的琴弦。
  • 最好先搜索复数版本,然后再搜索单数版本。 那
    如果你有不规则的复数形式 - 例如在我的商人中::
    商业示例 - 您可以正确得到所有不规则复数。
    否则,您最终可能会得到“businesss”(3 s)这样的结果
    中间状态,导致更多的搜索和替换。
  • 不要盲目地替换所有出现的情况。 如果你们的型号名称冲突
    使用常见的编程术语、使用其他模型中的值或使用
    如果您的观点中包含文本内容,您可能会变得过于渴望。
    在我的示例中,我想将模型名称更改为“Business”,但是
    在我的用户界面的内容中仍然将他们称为“商家”。 我还在 CanCan 中为我的用户设置了“商人”角色 - 正是商人角色和商人模型之间的混淆导致我首先重命名了该模型。

The other answers and comments covered table renaming, file renaming, and grepping through your code.

I'd like to add a few more caveats:

Let's use a real-world example I faced today: renaming a model from 'Merchant' to 'Business.'

  • Don't forget to change the names of dependent tables and models in
    the same migration. I changed my Merchant and MerchantStat models to Business and BusinessStat at the same time. Otherwise I'd have had to do way too much picking and choosing when performing search-and-replace.
  • For any other models that depend on your model via foreign keys, the other tables' foreign-key column names will be derived from your original model name. So you'll also want to do some rename_column calls on these dependent models. For instance, I had to rename the 'merchant_id' column to 'business_id' in various join tables (for has_and_belongs_to_many relationship) and other dependent tables (for normal has_one and has_many relationships). Otherwise I would have ended up with columns like 'business_stat.merchant_id' pointing to 'business.id'. Here's a good answer about doing column renames.
  • When grepping, remember to search for singular, plural, capitalized,
    lowercase, and even UPPERCASE (which may occur in comments) versions
    of your strings.
  • It's best to search for plural versions first, then singular. That
    way if you have an irregular plural - such as in my merchants ::
    businesses example - you can get all the irregular plurals correct.
    Otherwise you may end up with, for example, 'businesss' (3 s's) as an
    intermediate state, resulting in yet more search-and-replace.
  • Don't blindly replace every occurrence. If your model names collide
    with common programming terms, with values in other models, or with
    textual content in your views, you may end up being too over-eager.
    In my example, I wanted to change my model name to 'Business' but
    still refer to them as 'merchants' in the content in my UI. I also had a 'merchant' role for my users in CanCan - it was the confusion between the merchant role and the Merchant model that caused me to rename the model in the first place.
烟雨扶苏 2024-07-19 04:34:37

您还需要替换索引:

class RenameOldTableToNewTable< ActiveRecord:Migration
  def self.up
    remove_index :old_table_name, :column_name
    rename_table :old_table_name, :new_table_name
    add_index :new_table_name, :column_name
  end 

  def self.down
    remove_index :new_table_name, :column_name
    rename_table :new_table_name, :old_table_name
    add_index :old_table_name, :column_name
  end
end

并按照此处其他答案所述手动重命名文件等。

请参阅:http://api.rubyonrails.org/classes/ActiveRecord/Migration.html

确保您编写此迁移后可以回滚和前滚。 如果您出错并陷入试图影响不再存在的内容的迁移中,事情可能会变得棘手。 如果无法回滚,最好丢弃整个数据库并重新开始。 因此请注意您可能需要备份某些内容。

另外:检查 schema_db 中由 has_ 或 Belongs_to 等定义的其他表中的任何相关列名。 您可能也需要编辑它们。

最后,在没有回归测试套件的情况下执行此操作将是疯狂的。

You also need to replace your indexes:

class RenameOldTableToNewTable< ActiveRecord:Migration
  def self.up
    remove_index :old_table_name, :column_name
    rename_table :old_table_name, :new_table_name
    add_index :new_table_name, :column_name
  end 

  def self.down
    remove_index :new_table_name, :column_name
    rename_table :new_table_name, :old_table_name
    add_index :old_table_name, :column_name
  end
end

And rename your files etc, manually as other answers here describe.

See: http://api.rubyonrails.org/classes/ActiveRecord/Migration.html

Make sure you can rollback and roll forward after you write this migration. It can get tricky if you get something wrong and get stuck with a migration that tries to effect something that no longer exists. Best trash the whole database and start again if you can't roll back. So be aware you might need to back something up.

Also: check schema_db for any relevant column names in other tables defined by a has_ or belongs_to or something. You'll probably need to edit those too.

And finally, doing this without a regression test suite would be nuts.

空袭的梦i 2024-07-19 04:34:37

你可以做
执行此命令:rails g迁移
rename_{old_table_name}重命名为{new_table_name} rename_table

编辑文件并在方法更改中添加此代码后将

:{old_table_name}, :{new_table_name}

You can do
execute this command : rails g migration
rename_{old_table_name}to{new_table_name}

after you edit the file and add this code in the method change

rename_table :{old_table_name}, :{new_table_name}

满意归宿 2024-07-19 04:34:37

一种更现代、更有效的方法是:

class RenameOldTableToNewTable < ActiveRecord::Migration
  def change
    reversible do |dir|
      dir.up do
        rename_table :old_table_name, :new_table_name
      end
      dir.down do
        rename_table :new_table_name, :old_table_name
      end
    end
  end
end

++ 不要忘记手动重命名模型声明文件。


个人经验:

我尝试了@readonly的解决方案来重命名我的表。 我只需要在表格末尾添加一个“S”,所以我的旧表格和新表格之间的唯一区别就是这封信。
并且该解决方案不起作用。 Rails 认为这是同一张表,因此没有进行任何更改。
我尝试了上面给出的现代解决方案,它工作正常。

Rails 版本:6.1.7.2

A more modern and efficient way to do this would be :

class RenameOldTableToNewTable < ActiveRecord::Migration
  def change
    reversible do |dir|
      dir.up do
        rename_table :old_table_name, :new_table_name
      end
      dir.down do
        rename_table :new_table_name, :old_table_name
      end
    end
  end
end

++ don't forget to rename the model declaration file manually.


Personal experience :

I tried @readonly's solution to rename my table. I only had to add an 'S' at the end of my table, so the only difference between my old table and my new table was this letter.
And the solution didn't worked. Rails considered this to be the same table and therefore made no changes.
I tried with the modern solution I gave above, and it works normally.

Rails version : 6.1.7.2

破晓 2024-07-19 04:34:37

如果您想在 Rails 7 中将 collaboration 表的名称更改为 comment,请按照以下步骤操作:

  1. 打开终端并导航到 Rails 应用程序目录。< /p>

  2. 运行以下命令生成新的迁移文件:

    rails 生成迁移 ChangeCollaborationToComment

    这将生成一个新的迁移文件,其名称类似于 timestamp_change_collaboration_to_comment.rb

  3. db/migrate目录中打开生成的迁移文件。

  4. 更新迁移文件以使用rename_table方法:

class ChangeCollaborationToComment class ChangeCollaborationToComment class ChangeCollaborationToComment class ChangeCollaborationToComment < ActiveRecord::Migration[7.0] def change rename_table :collaborations, :comments end end

这会将表名称从 collaborations 更改为 comments

  1. 保存迁移文件。

  2. 使用以下命令运行迁移:

    rails db:migrate

    这会将更改应用到您的数据库。

运行迁移后,数据库中的表名称应从 collaborations 更新为 comments。 根据您的实际设置相应调整迁移文件和表名称。

If you want to change the name of the collaboration table to comment in Rails 7, follow these steps:

  1. Open your terminal and navigate to your Rails application directory.

  2. Run the following command to generate a new migration file:

    rails generate migration ChangeCollaborationToComment

    This will generate a new migration file with a name like timestamp_change_collaboration_to_comment.rb.

  3. Open the generated migration file in the db/migrate directory.

  4. Update the migration file to use the rename_table method:

class ChangeCollaborationToComment < ActiveRecord::Migration[7.0] def change rename_table :collaborations, :comments end end

This will change the table name from collaborations to comments.

  1. Save the migration file.

  2. Run the migration using the following command:

    rails db:migrate

    This will apply the changes to your database.

After running the migration, the table name should be updated from collaborations to comments in your database. Adjust the migration file and table names accordingly based on your actual setup.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文