Model Start-up
Model is database data and ruby model class.
Topics
- Create simple model without any data type
- Create model with type
- datatype
- Delete model
- Migration
- Reset
Create simple model without any data type
rails g model item
To do this, 4 files are generated.
Filename | Description |
---|---|
app/models/item.rb | Model |
db/migrate/xxxx_create_item.rb | Migration |
test/models/item_test.rb | Test |
test/fixtures/items.yml | Fixtures |
Create model with sub directory
rails g model Products::Lucky
create app/models/products.rb, app/models/products/lucky.rb
Create model with type
rails generate model Country name population:integer
The definition is in migration file
class CreateCountries < ActiveRecord::Migration def change create_table :countries do |t| t.string :name t.integer :population t.timestamps end end end
timestamps field exists by default
datatype
This is
ActiveRecord wraps each database type. Actually some database doesn't have a type, other database has. In this case, it does something to cover.
- integer
- primary_key
- decimal
- float
- boolean
- binary
- string
- text
- date
- time
- datetime
- timestamp
Delete model
Same as controller
rails destroy model item
item is model name
All files are deleted which is relevant to
Migration
Migration is to change schema. All migration files are under db/migrate.
These files are executed according to timestamp.
Be careful to handle schema change.
Execute migration
Use rake command
rake db:migrate
Rollback one migration
Only one step
rake db:rollback
Reset
Do create, drop, migrate at the same time
rake db:migrate:reset
Maybe switch back to the initial state.
There is One Comment.
Pingback: Database and check | Professional Programmer