03. Models - max-borisov/ihub-bookshelf GitHub Wiki
There will be 6 models:
- user - manage user accounts
- book - manage books
- review - manage reviews
- shopping_cart_item - manage user shopping cart
- order - manage orders
- order_item - manage order items
Lets generate models using rails generate command:
$ rails generate model book title:string author:string description:text price:'decimal{10,2}' pub_date:date amazon_id:string:uniq isbn:string:uniq
A new migration file file will be generated under db/migrate directory.
It will look like this:
class CreateBooks < ActiveRecord::Migration
def change
create_table :books do |t|
t.string :title
t.string :author
t.text :description
t.decimal :price, precision: 10, scale: 2
t.date :pub_date
t.string :amazon_id
t.string :isbn
t.timestamps null: false
end
add_index :books, :amazon_id, unique: true
add_index :books, :isbn, unique: true
end
end
$ rails generate model review text:text user:references book:references
$ rails generate model user name:string email:string:uniq admin:boolean
Open xxxxx_creare_users_.rb file under db/migrate folder and set default value for admin column:
class CreateUsers < ActiveRecord::Migration
def change
create_table :users do |t|
t.string :name
t.string :email
t.boolean :admin, default: false
t.timestamps null: false
end
add_index :users, :email, unique: true
end
end
$ rails generate model shopping_cart_item user:references book:references
$ rails generate model order user:references total_price:'decimal{10,2}'
$ rails generate model order_item order:references book:references
Example of migrations folder:
It's time to apply migrations:
$ rake db:migrate
This command will create the database and models. Also db/schema.rb file is available now.
By the way, the following will return the list of all available rake commands:
$ rake -T