将新的Rails应用程序连接到现有的MySQL数据库 [英] Connecting a new Rails app to an existing MySQL database

查看:105
本文介绍了将新的Rails应用程序连接到现有的MySQL数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个全新的Rails应用程序,我想连接到现有的MySQL数据库中以进行一些读取和写入.我已经编辑了database.yml文件以连接到新数据库. rails crails s不会抛出错误,使我相信该连接是有效的.

I have a brand new Rails app that I want to hook into an existing MySQL database to do some reading and writing. I've already edited my database.yml file to connect to the new db. rails c and rails s don't throw errors which lead me to believe that the connection is valid.

我还没有创建任何模型或迁移.我想知道是否有一种简单的方法可以将所需的模型放入我的Rails项目中.

I haven't created any models or migrations yet. I was wondering if there was an easy way to get the models I need into my Rails project.

如果我需要导出备份或架构,则可以使用Sequel Pro连接到数据库.还是我需要生成模型并手动复制所有列类型和所有内容?

I'm able to connect to the db with Sequel Pro if I need to export a backup or a schema. Or do I need to generate models and copy all of the column types and everything manually?

感谢您的帮助.

推荐答案

ActiveRecord将为您检测列名称!您无需创建任何迁移,但必须创建模型.

ActiveRecord will detect the column names for you! You don't need to create any migrations, but you do have to make the models.

创建活动记录模型时,活动记录将通过使类名复数来推断您要连接的表名.

When you make an active record model, active record will deduce the table name that you're connecting to by pluralizing the class name.

所以:

# app/models/book.rb

class Book < ActiveRecord::Base
end

将尝试查找一个名为"books"的表.然后,您可以实例化Book的实例,并发现它具有用于字段名称的getter/setter方法.

Will try to find a table called "books". You can then instantiate an instance of Book, and you'll find it has getters/setters for your field names.

如果表不遵循此命名约定,则还可以手动定义表名:

If your tables don't follow this naming convention, you can also define your table names manually:

class Mouse < ActiveRecord::Base
  self.table_name = "mice" 
end

http://api.rubyonrails.org/classes/ActiveRecord/ModelSchema/ClassMethods.html

这篇关于将新的Rails应用程序连接到现有的MySQL数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆