Connecting a new Rails app to an existing MySQL da

2019-07-23 08:06发布

问题:

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.

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.

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?

Thanks for your help.

回答1:

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.

So:

# app/models/book.rb

class Book < ActiveRecord::Base
end

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



回答2:

Start by creating empty model files with the following structure, for an orders table:

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.