【发布时间】:2017-04-11 20:34:56
【问题描述】:
我有一个 Rails 5 应用程序,它对三个数据库进行了单独的迁移。我正在添加一个新数据库。我通常会使用rails g model field1:type1 field2:type2 field3:type.... 来创建包含所需字段的数据库表。我想创建生成模型语句,它将为所需的数据库生成模型并将其放在相应的 db/migrate 文件夹中。
我有自定义数据库迁移生成器,用于 lib/generators 中的其他数据库。这是自定义迁移生成器的示例。
lib/generators/stats_migration_generator.rb
require 'rails/generators/active_record/migration/migration_generator'
class StatsMigrationGenerator < ActiveRecord::Generators::MigrationGenerator
source_root File.join(File.dirname(ActiveRecord::Generators::MigrationGenerator.instance_method(:create_migration_file).source_location.first), "templates")
def create_migration_file
set_local_assigns!
validate_file_name!
migration_template @migration_template, "db_stats/migrate/#{file_name}.rb"
end
end
我假设我需要为每个附加数据库创建 lib/generators/mydb_model_generator.rb 或任何正确的文件名结构。在查看 GitHub 中的 model_generator.rb 文件后,我想我可以做这样的事情。
lib/generators/stats_model_generator.rb
require 'rails/generators/active_record/model/model_generator'
class StatsModelGenerator < ActiveRecord::Generators::ModelGenerator
source_root File.join(File.dirname(ActiveRecord::Generators::ModelGenerator.instance_method(:create_migration_file).source_location.first), "templates")
def create_migration_file
set_local_assigns!
validate_file_name!
migration_template @migration_template, "db_stats/migrate/#{file_name}.rb"
end
end
在查看 Rails 的 git 存储库the Rails Guide regarding creating and customizing Generators 和 Ruby on Rails API 文档后,我的问题如下:
- 如何找到我需要的东西?
- 如何找到需要什么方法来覆盖 db/migrate 文件夹名称?
- 如何了解如何为模型生成器命名 rb 文件?
我在尝试创建模型生成器时的假设是否正确?
【问题讨论】:
标签: ruby-on-rails database customization rails-generators