Rails: Active Record Basic

Guide

  • Object Relational Mapping (ORM)
  • Model manipulating data stored in relational database.
  • Migrations, Validations, Callbacks, Associations, Queries

1. Active Record

  • MVC 中的模型層 Model。
  • Object Relational Mapping (ORM) 的一活生生的例子。
  • 負(fù)責(zé)處理核心業(yè)務(wù)及其相關(guān)的邏輯,并將相關(guān)數(shù)據(jù)持久化存儲到數(shù)據(jù)庫中。

2. Schema Conventions

  • Active Record 關(guān)聯(lián)數(shù)據(jù)庫某些特殊列的命名規(guī)則:
    • Primary key 默認(rèn)為id,Foreign key 默認(rèn)為關(guān)聯(lián)表名稱_id。
    • Timestamps 默認(rèn)為表格添加兩個時間戳 created_atupdated_at。
    • Optimistic Locking 樂觀鎖通過添加 lock_version來實現(xiàn)。
    • Single Table Inheritance 單表繼承通過添加 type 來實現(xiàn)。
    • Polymorphic Association 多態(tài)通過添加 關(guān)聯(lián)表名稱_id/_type 來實現(xiàn)。
    • Counter Cache 計數(shù)器通過添加 關(guān)聯(lián)表名稱_count 來實現(xiàn),注意只讀。
  • Tips: 向上述這些列的名稱應(yīng)該在非特定情況中避免使用,以免混淆不清。

3. Overriding the Naming Conventions

  • 如果你不幸遇到遺留系統(tǒng) (legacy app),并且它的數(shù)據(jù)庫中表的名稱并沒有遵循 Rails 約定俗成的規(guī)則,那么該怎么辦呢?不要慌,簡單地使用一些方法就可以達(dá)到相互認(rèn)識且完美匹配的效果。例如ActiveRecord::Base.table_name=.. primary_key=.. 方法來指定遺留系統(tǒng)中的表名和主鍵名。

4. CRUD

  • C: new + save, create
  • R: all, find, find_by, first, where
  • U: find + save, update, update_all, update_attribute, update_column
  • D: find + destroy, find + delete, destroy_all, delete_all

Others:

  • 204 No Content response
  • validates: presence or uniqueness of columns,
  • validates: their format
  • validates: the existence of associated objects
  • div.field_with_errors
  • http_basic_authenticate_with
  • Devise and Authlogic

Resources:

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Awesome Ruby Toolbox Awesome A collection of awesome Ruby...
    debbbbie閱讀 3,088評論 0 3
  • Spark SQL, DataFrames and Datasets Guide Overview SQL Dat...
    Joyyx閱讀 8,487評論 0 16
  • 一、心得體會1、今天完成了什么? Rails guide 4 170頁 5個小時 重看了鎬頭書看了第一部分 1個小...
    柳輝閱讀 382評論 0 1
  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,569評論 19 139
  • 1. 要養(yǎng)成良好的晨讀習(xí)慣。早晨起床的時候讀單詞和課文幾分鐘也好。 2. 一定要做好預(yù)習(xí),在課后一定要及時的復(fù)習(xí),...
    暴力女神閱讀 197評論 0 0

友情鏈接更多精彩內(nèi)容