且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-01-21 20:07:15

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