Ruby学习笔记4: 动态web app的建立
We will first build the Categories page. This page contains topics like Art, Home & Living, and Kids, so our users can browse through categories and find what they like.
Each Category in our site will need to store information about itself, such as a name and an image. Our Category Model is what stores information about our Categories. Remember that our Model manages the data in our app.
===============================
1. Build Model
2. Build Migration Table
3. Add Data to Tables
4. Generate Table Controller
5.
===============================
1. Build our Model
开始之前,我们要先建立Model用来存储每个Category的数据模型。
We can generate a Model with the following rails command:
rails generate model Person
Here Person
is an example name for our Model. Model names are always singular.
In your terminal, generate a model named
Category
using the rails command. Press Enter.
rails generate model Category
In terminal:
$ rails generate model Category
invoke active_record
create db/migrate/20141013165110_create_categories.rb
create app/models/category.rb
invoke test_unit
create test/models/category_test.rb
create test/fixtures/categories.yml
$
2. Build our Migration table
Our Model is fine for now. Let's prepare our Migration table. We do this in two steps:
a. We add columns to our Category Migration table. These will define what information our database can accept.
b. We type bundle exec bundle exec rake db:migrate in our terminal to migrate our database, or update its state.
Let's look at an example. Say we had a Person Model, and we want it to have the columns name and age. In the Migration table, we add columns like this:
def change
create_table :person do |t|
t.string :name
t.integer :age
t.timestamps
end
end
Above we add t.string :name
andt.integer :age
specifying the name of type string and the age of type integer. We run db:migrate to add a name and age column to our actual database.