简体   繁体   English

从应用程序创建迁移

[英]Create migration from application

I want to create migrations to add columns from my rails application (not through rails g migration xxxx ), while creating the migration I want to store the version number to the for the migration for later possible down operation. 我想创建迁移以从Rails应用程序中添加列(而不是通过rails g migration xxxx ),同时创建迁移时,我想将版本号存储到,以供以后进行向下操作时使用。

The scenario is, I have an application with generalized tables and their fields. 场景是,我有一个带有通用表及其字段的应用程序。 The application can be deployed for multiple customers. 可以为多个客户部署该应用程序。 I want to provide a way to define custom fields in the table. 我想提供一种在表中定义自定义字段的方法。 Once the user selects/inputs desired data like table_name, field_name, data_type etc. I will be creating a new migration to add the field and store the version number somewhere in the database. 一旦用户选择/输入所需的数据,例如table_name,field_name,data_type等。我将创建一个新迁移,以添加字段并将版本号存储在数据库中的某个位置。 This version number will be used to migrate:down in case the user decides to delete the field. 如果用户决定删除该字段,此版本号将用于migrate:down

Is there any other better approach than this? 还有其他更好的方法吗?

I have implemented this as below: Depending upon the field_name and table_name I create a migration using: 我已经实现了以下操作:根据field_nametable_name我使用以下方法创建迁移:

def create_migration
    field_name_for_db = field_name.gsub(' ', '_').downcase
    migration_name = "add_column_#{self.field_name}_to_#{self.table_name}"
    logger.info "cd #{Rails.root} && rails g migration #{migration_name} #{self.field_name}:string > #{Rails.root}/tmp/migration_details.txt && rake db:migrate"
    system "cd #{Rails.root} && rails g migration #{migration_name} #{self.field_name}:string > #{Rails.root}/tmp/migration_details.txt && rake db:migrate"
    migration_version = File.read("#{Rails.root}/tmp/migration_details.txt").split('/').last.split("_#{migration_name}").first
    self.migration_name = migration_name
    self.migration_version = migration_version
    self.save
  end

In this method I have redirected the output of create migration command to a file and retrieving migration number from the file and then storing it to the database. 在这种方法中,我将create migration命令的输出重定向到一个文件,并从该文件中检索迁移号,然后将其存储到数据库中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM