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.
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 c开发者_如何学Pythonreating a new migration to add the field and store the version number somewhere in the database. This version number will be used to migrate:down
in case the user decides to delete the field.
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:
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.
精彩评论