rails CRUD 应用程式

Rails的MVC元件

  • ActiveRecord是Rails的Model元件
  • ActionPack包含了ActionDispatch、ActionController和ActionView,分别是Rails的Routing、Controller和View元件
  1. 浏览器发出HTTP request请求给Rails
  2. 路由(Routing)根据规则决定派往哪一个Controller的Action
  3. 负责处理的Controller Action操作Model资料
  4. Model存取数据库或资料处理
  5. Controller Action将得到的资料餵给View样板
  6. 回传最后的HTML成品给浏览器

ActiveRecord操作数据库

ActiveRecord是Rails的ORM(Object-relational mapping)元件,负责与数据库沟通,让你可以使用物件导向语法来操作关联式数据库,它的对应概念如下:

  • 将数据库表格(table)对应到一个类别(class)
  • 类别方法就是操作这个表格(table),例如新增资料、多笔资料更新或多笔资料删除
  • 资料表中的一笔资料(row)对应到一个物件(object)
  • 物件方法就是操作这笔资料,例如更新或删除这笔资料
  • 资料表的字段(column)就是物件的属性(object attribute)

使用Rails的generator功能来分别产生Model和Controller档案

这些指令必须要在Rails专案目录下执行

1
2
$ rails g model event name:string description:text is_public:boolean capacity:integer
$ bin/rake db:migrate

接着,使用rails console(可以简写为rails c) 进入主控台模式做练习:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# 新增
> event = Event.new
> event.name = "Ruby course"
> event.description = "fooobarrr"
> event.capacity = 20
> event.save # 储存进数据库,读者可以观察另一个指令视窗
> event.id # 输出主键 1,在 Rails 中的主键皆为自动递增的整数 ID
> event = Event.new( :name => "another ruby course", :capacity => 30)
> event.save
> event.id # 输出主键 2,这是第二笔资料
# 查询
> event = Event.where( :capacity => 20 ).first
> events = Event.where( ["capacity >= ?", 20 ] ).limit(3).order("id desc")
# 更新
> e = Event.find(1) # 找到主键为 1 的资料
> e.name # 输出 Ruby course
> e.update( :name => 'abc', :is_public => false )
# 删除
> e.destroy

Migration建立资料表

Rails使用了Migration数据库迁移机制来定义数据库结构(Schema),档案位于db/migrate/目录下。它的目的在于:

  • 让数据库的修改也可以纳入版本控制系统,所有的变更都透过撰写Migration档案执行
  • 方便应用程式更新升级,例如让软件从第三版更新到第五版,数据库更新只需要执行rake db:migrate
  • 跨数据库通用,不需修改程式就可以用在SQLite3、MySQL、Postgres等不同数据库
1
2
3
4
5
6
7
8
9
10
11
12
13
#db/migrate/20161125011631_create_events.rb
class CreateEvents < ActiveRecord::Migration[5.0]
def change
create_table :events do |t|
t.string :name
t.text :description
t.boolean :is_public
t.integer :capacity
t.timestamps
end
end
end

Migration档案不需要和Model一一对应,像我们来新增一个Migration档案来新增一个数据库字段

$ rails g migration add_status_to_events

编辑这个Migration档案:

1
2
3
def change
add_column :events, :status, :string
end

接着执行bin/rake db:migrate就会在events表格中新增一个status的字段,字段型别是string。Rails会记录你已经对数据库操作过哪些Migrations,像此例中就只会跑这个Migration而已,就算你多执行几次bin/rake db:migrate也只会对数据库操作一次。

ActiveRecord资料验证(Validation)

编辑app/models/event.rb加入

class Event < ActiveRecord::Base
validates_presence_of :name
end

其中的validates_presence_of宣告了name这个属性是必填。我们按Ctrl+Z离开主控台重新进入,或是输入 reload!,这样才会重新加载

基本的CRUD应用程式

有了Event model,接下来实作出完整的CRUD使用者接口流程,这包含了列表页面、新增页面、编辑页面以及个别资料页面。

外卡路由

编辑config/routes.rb在最后插入一行:

match ‘:controller(/:action(/:id(.:format)))’, :via => :all

列出所有资料

Rails的generator功能来产生controller rails g controller events

在Rails会让Action里的实例变量(也就是有@开头的变量)通通传到View样板里面可以使用。

RESTful 应用程式

REST有主要有两个核心精神:1. 使用Resource来当做识别的资源,也就是使用一个URL网址来代表一个Resource 2. 同一个Resource则可以有不同的Representations格式变化。这一章的路由实作了Resource概念,而Representation则是用了respond_to方法来实作,稍候我们也会介绍如何使用。

RESTful带给Rails最大的好处是:它帮助我们用一种比较标准化的方式来命名跟组织Controllers和Actions