简体   繁体   English

将新的Rails应用程序连接到现有的MySQL数据库

[英]Connecting a new Rails app to an existing MySQL database

I have a brand new Rails app that I want to hook into an existing MySQL database to do some reading and writing. 我有一个全新的Rails应用程序,我想连接到现有的MySQL数据库中进行一些读写。 I've already edited my database.yml file to connect to the new db. 我已经编辑了database.yml文件以连接到新数据库。 rails c and rails s don't throw errors which lead me to believe that the connection is valid. rails crails s不会引发错误,这使我相信连接是有效的。

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. 我想知道是否有一种简单的方法可以将所需的模型添加到Rails项目中。

I'm able to connect to the db with Sequel Pro if I need to export a backup or a schema. 如果需要导出备份或架构,则可以使用Sequel Pro连接到数据库。 Or do I need to generate models and copy all of the column types and everything manually? 还是我需要生成模型并手动复制所有列类型和所有内容?

Thanks for your help. 谢谢你的帮助。

ActiveRecord will detect the column names for you! ActiveRecord将为您检测列名称! 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. 当您创建活动记录模型时,活动记录将通过使类名复数来推断您要连接的表名。

So: 所以:

# app/models/book.rb

class Book < ActiveRecord::Base
end

Will try to find a table called "books". 将尝试查找一个名为“ books”的表格。 You can then instantiate an instance of Book, and you'll find it has getters/setters for your field names. 然后,您可以实例化Book的实例,您会发现它具有用于字段名称的getter / setter方法。

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 http://api.rubyonrails.org/classes/ActiveRecord/ModelSchema/ClassMethods.html

Start by creating empty model files with the following structure, for an orders table: 首先为orders表创建具有以下结构的空模型文件:

class Order < ActiveRecord::Base
end

With just that much in place, you can get all the active record magic on the orders table. 有了足够的准备,您就可以在订单表上获得所有活动记录的魔力。 You could do the following from the console: 您可以从控制台执行以下操作:

> Order.count
 => # Shows the number of rows in orders table
> Order.first
 => # Return the first row from the table
> Order.where(...)
 => # Return selected rows from the table meeting the specified criteria.

See Active Record Query Interface for more active record features that you get by subclassing from ActiveRecord::Base . 有关从ActiveRecord::Base子类化获得的更多活动记录功能,请参见活动记录查询接口

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM