我有一个很大的Mysql数据库,我想在rails应用程序中快速使用,但我不想为我必须编写的所有模型编写所有数据库模式。有一个快速的方法是否快速建立了所有模型和表格?
非常感谢。
答案 0 :(得分:1)
是的,这是可能的,这是如何:
确保您在config/database.yml
运行rake db:schema:dump
提示旁边:运行rake -T db:schema
,您将获得与数据库架构任务相关的所有可用命令的列表:
rake db:schema:cache:clear # Clear a db/schema_cache.dump file
rake db:schema:cache:dump # Create a db/schema_cache.dump file
rake db:schema:dump # Create a db/schema.rb file that is portable against any DB supported by AR
rake db:schema:load # Load a schema.rb file into the database
然而,生成模型是一个不同的故事,特别是如果您的现有数据库不遵循命名的rails约定。
有一些像rmre这样的宝石正是为了这个目的,但似乎没有维护。
如果您的遗留数据库不是怪物,您可以自己快速创建模型 - 这里的技巧是不创建任何迁移,即:
rails g model YourModel --migration=false
然后你必须调整一些关键属性,如表名和主键,以适应ActiveRecord的命名约定,可以按如下方式进行:
class YourModel < ActiveRecord::Base
self.table_name = 'a_legacy_table_name'
self.primary_key = 'primary_key_column_name'
belongs_to :other_model,
foreign_key: 'foreign_key_on_other_table'
has_many :other_models,
foreign_key: 'foreign_key_in_this_table',
primary_key: 'primary_key_on_other_table'
end