Last Updated: February 25, 2016
·
839
· jmarizgit

Rails : model and migrate

Lets say you want to create an database for your RoR application.

First, create a new rails application (replace "myapp" with your app name)

$ rails new myapp

Access your recent created folder myapp.

In Rails, databases are created using Models (take a look over the MVC pattern).

Create a new model for your application.

$ rails g model user name:string

Note that I included name:string after the name of our model. That says to Rails that I want to include a field called name with type string on the table.

We now have a migration file create on /db/migrate folder.

invoke  active_record
create    db/migrate/20121127031936_create_users.rb
create    app/models/user.rb
invoke    test_unit
create      test/unit/user_test.rb
create      test/fixtures/users.yml

Executing this migrate file will generate our table users.

$ rake db:migrate

Note: the table is called users instead of user as we specified. That is a convention used by Rails.

The database development.sqlite3 was create on our db/ folder.

Observe the structure of the table users.

id
name
createdat
updated
at

Rails created id, created_at, and updated_at fields automatically for you.