2

In RoR, when I run the following command for example:

> rails generate model xyz

And, if I go to for example 12345_create_xyzs.rb, I will find something similar to this:

def self.up
    create_table :xyzs do |t|

So, when I made a model, am I actually making a table?

But, where is the database?!

3 Answers 3

3

When you use rails generate model zyz, you are telling Rails to generate several files for you. The file 12345_create_xyzs.rb is what is called a migration - it contains the instructions to populate a database with the table structure associated with your model.

You do, however, need to make sure that the DB exists (so, for example in MySql CREATE DATABASE MyDB), and your database.yml file has the correct connection information to that database.

If this is true, when you run rake db:migrate, the rake task will take care of migrating your model structure to the database.

2

When you rails generate model xyz, you will be specifying the fields (and other things like the database indexes you want) that the table xyz will have in the database. The table is representing the model class in the database.

To create that table in the database, you would migrate the model definition file (12345_create_xyzs.rb) using rake db:migrate.

The model is represented in Rails (i.e. ActiveRecord) code as a class, in a file called app/models/xyz.rb:

class Xyz < ActiveRecord::Base
  ...
end

You create the app/models/xyz.rb file in addition to the migration file created above by rails generate model. In this class is where you put things like specifying relationships between models, adding constraints and other code you need.

1
  • I think def Xyz < ActiveRecord::Base has to be class Xyz < ActiveRecord::Base. Right?
    – Simplicity
    Aug 7, 2011 at 14:15
1

You have to run the command rake db:migrate in order to migrate the database. The command rake db:create creates the database...

More information available here.

In addition, the database must be configured into the file situated here :

<your_project>/config/database.yml

More information here. More generally, I think you really should read the "getting started".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.