iT邦幫忙

2021 iThome 鐵人賽

DAY 8
0
自我挑戰組

海邊囝仔帶阿公阿嬤一起學 Ruby On Rails 系列 第 8

Day-8:Rails的CRUD

CRUD係蝦米?

CRUD即為Create、Read、Update、Delete等四項基本資料庫操作

  • C是Create,新增
  • R是Read,讀取
  • U是Update,更新
  • D是Delete,刪除

Rails的MVC元件
https://ithelp.ithome.com.tw/upload/images/20210922/20140259v2P9gmzJE0.png


ActiveRecord操作資料庫:

ActiveRecord是負責與資料庫溝通,
讓你可以使用物件導向語法來操作關聯式資料庫,
它的對應概念如下:

  • 將資料庫表格(table)對應到一個類別(class)
  • 類別方法就是操作這個表格(table),例如新增資料、多筆資料更新或多筆資料刪除
  • 資料表中的一筆資料對應到一個物件
  • 物件方法就是操作這筆資料,例如更新或刪除這筆資料
  • 資料表的欄位就是物件的屬性

使用Rails的generator功能來分別產生Model和Controller檔案:
產生一個Model:
$ rails g model wali name:string description:text capacity:string
(string皆可以省略,可以簡略成以下寫法)
$ rails g model name description:text capacity
執行以下指令就會建立資料表 :
rails db:migrate


進入rails console(亦可在終端機輸入rails c)寫入資料庫 :

https://ithelp.ithome.com.tw/upload/images/20210922/20140259quofuTxWjn.png


查詢

https://ithelp.ithome.com.tw/upload/images/20210922/20140259PrtIcpc6iT.png


更新

https://ithelp.ithome.com.tw/upload/images/20210922/201402598Q9hVbRYlO.png


刪除

https://ithelp.ithome.com.tw/upload/images/20210922/20140259wr1xd0dgGT.png

謝謝你的觀看,若有任何不對的地方,歡迎指正~感謝/images/emoticon/emoticon41.gif

參考資料:Rails 實戰聖經


上一篇
Day-7:Rails Turbolinks
下一篇
Day-9: Migration 係蝦米哇貴?
系列文
海邊囝仔帶阿公阿嬤一起學 Ruby On Rails 30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言