我有一个很大的Mysql数据库,我想在rails应用程序中快速使用它,但是我不想为我要编写的所有模型编写所有的db模式……有没有一种快速的方法可以快速地设置所有的模型和表?
非常感谢。

最佳答案

是的,这是可能的,这里是如何:
确保在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

关于mysql - 如何将当前的大型Mysql DB转换为Rails 4.2,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35567398/

10-12 04:00