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_at和updated_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