Rails MVC 和 CRUD(8)

2021-11-25 16:19:31 浏览数 (1)

再次提交一回


创建模型

Rails 提供了一个生成器用来创建模型

代码语言:javascript复制
[root@h202 blog]# bin/rails generate model Article title:string text:text
Running via Spring preloader in process 13216
      invoke  active_record
      create    db/migrate/20160422140912_create_articles.rb
      create    app/models/article.rb
      invoke    test_unit
      create      test/models/article_test.rb
      create      test/fixtures/articles.yml
[root@h202 blog]#

生成的两个文件中包含了这个 model 的结构

代码语言:javascript复制
[root@h202 blog]# cat db/migrate/20160422140912_create_articles.rb
class CreateArticles < ActiveRecord::Migration
  def change
    create_table :articles do |t|
      t.string :title
      t.text :text

      t.timestamps null: false
    end
  end
end
[root@h202 blog]# cat app/models/article.rb
class Article < ActiveRecord::Base
end
[root@h202 blog]#

可知这个新生成的 model 继承自 ActiveRecord


进行迁移

迁移就是将前面定义的model ,落实到数据库中形成表结构

代码语言:javascript复制
[root@h202 blog]# bin/rake db:migrate
Running via Spring preloader in process 13248
== 20160422140912 CreateArticles: migrating ===================================
-- create_table(:articles)
   -> 0.0131s
== 20160422140912 CreateArticles: migrated (0.0132s) ==========================

[root@h202 blog]#

那到底将数据结构定义到了哪里呢

代码语言:javascript复制
[root@h202 blog]# cat config/database.yml 
# SQLite version 3.x
#   gem install sqlite3
#
#   Ensure the SQLite 3 gem is defined in your Gemfile
#   gem 'sqlite3'
#
default: &default
  adapter: sqlite3
  pool: 5
  timeout: 5000

development:
  <<: *default
  database: db/development.sqlite3

# Warning: The database defined as "test" will be erased and
# re-generated from your development database when you run "rake".
# Do not set this db to the same as development or production.
test:
  <<: *default
  database: db/test.sqlite3

production:
  <<: *default
  database: db/production.sqlite3
[root@h202 blog]# grep -v "^#" config/database.yml 
default: &default
  adapter: sqlite3
  pool: 5
  timeout: 5000

development:
  <<: *default
  database: db/development.sqlite3

test:
  <<: *default
  database: db/test.sqlite3

production:
  <<: *default
  database: db/production.sqlite3
[root@h202 blog]# ll db/development.sqlite3 
-rw-r--r-- 1 root root 5120 Apr 22 22:19 db/development.sqlite3
[root@h202 blog]#

0 人点赞