6.1 adding models and migrate to database in rails

1. now, we will add User model to our app, so that we can register, sign in, etc.

 

rails g model User name:string email:string

 

note:

when generate controller, we use plural format:  rails g controller Users new

but when gen model, we use singular:   rails g model User name:string email:string

 

2. one of the result of this generate, is that it will create a new file call migration.

 

a migration is a way to alter database by incremental way.

 

the file name of the migration is pre-fixed by a timestamp, indicating when the migration is created.

 

3. after done the create of user model, let's go to look at the code in the migration:

 

a. def sef.up,   means this is a class method.

b. create_table is a helper method.

c. this helper method accept a block, passing a param of the table object.

d. t.string :name,  create a column

d. t.timestamps,     create two time columns, created_at and updated_at

 

note, the model in singular, but the table name is always plural, since there are many users.

 

4. sqlite is using a simple file to store database, not like other database.

the data file is just

db/development.sqlite3

db/test.sqlite3

 

 

5. if you did migrate, then you regret, then you can use the self.down method inside migration:


rake db:rollback


this will call the self.down method, and drop the table.

 

the rollback and self.down method will be often used in this senario:

 

you forget to add a column, but you don't want to take the trouble of making another migration!!!

 

then rollback, and then add the column to the migration file, then migrate again!!

 

So easy!! amazing

 

But sometimes, you still have to add column to existing table, we will talk of it later.

 

 

6.  if you want to browse the SQLite database easily, you can use SQLite database browser program.

it can easily download from internet.

 

7. there is a gem called "annotate", this gem will add a command:

annotate --position before

 

this command will add comments to model files, these comments list all column inside this model, for example:

# == Schema Information
#
# Table name: users
#
#  id         :integer         not null, primary key
#  name       :string(255)
#  email      :string(255)
#  created_at :datetime
#  updated_at :datetime

class User < ActiveRecord::Base
end
 

 

 

8. next,  we will tell rails which attributs are accessible by outside users:

 

attr_accessible :name, :email

 

note, the use of attr_accessible, will also add a great advantage that it can prevent from mass assignment vulnerability. this is a very common hold in web app.

 

 

 

 

 

 

 

 

 

 

你可能感兴趣的:(database,Model,migration)