RoR - Introduction to Active Record

Active Record: 數據庫

ORM ( Object-relational Mapping)
Bridges the gap between relational databases ,app

which are designed around mathematical Set Theory and Objectthis

Oriented programming languages that deal with objects and their behaviorspa

* Greatly simplifies writing code for accessing the databasecode

*In rails, the model(usually) uses some ORM framwork.對象

 

Active Record is also the name of Rails' default ORMblog

1. Actuve Record has to know how to find your databse(When Rails is loaded,  this info is read from config/database.yml file)排序

2.(Convention) There is a table with a plural name that corresponds to ActiveRecord::Base subclass with singular namehash

3.(Converntion) Expects the table to have a primary key named idit

Model and Migration:

rails g model person first_name last_name    --- generate model 

reload! --- After rake db:migrate 

 

Active Record conventions: 

*Class name is singular 

*DB table name is plural 

*Need to have an id primary key

 

Active Record CRUD: 

Create:  

有3種方法 在數據庫中Create a record 

1. 用空的構造器和(ghost) attributes 去設置數據而後call save 保存

2.傳hash of attribute到構造器中而後call save 保存

3.用create方法,用hash去建立一個對象而後把它保存到數據庫中(只需1步)

#1
p1=Person.new; p1.first_name = "Joe"; p1.last_name ="Smith"
p1.save 

#2 
p2 = Person.new(first_name: "John", last_name:"Doe");
p2.save

#3
p3=Person.create(first_name:"Jane",last_name:"Doe")

Retrieve/Read :

1. find(id) or find(id1, id2)

 若是沒找到 拋出 RecordNotFound exception 

2. first, last, take, all 

返回你指望的結果或者nil 若是不存在

3. order(:column) or order(column: :desc)

排序返回的結果,升序或者降序

4.pluck 

*allows to narrow down thich fields are coming back

*Need to call at the end!

Person.take 2 隨機從數據庫中抽出2個對象

Person.all.map { |person| person.first_name } map返回全部的first_name

Person.pluck(:first_name)  用法同上,不過是在database level

 

where(hash) 

Person.where(last_name: "Doe") 返回名字裏有Doe

Person.where(last_name: "Doe").first 第一個返回名字裏有Doe的

Person.where(last_name: "Doe").pluck(:firtst_name)   pluck is not active record

 

find_by(conditions_hash)

Person.find_by(last_name: "Doe")  只給一個record

Person.find_by(last_name: "xxx")    #=>  nil

Person.find_by!(last_name: "xxx")   ActiveRecord::RecordNotFound: Couldn't find Person

limit: 限制返回多少條records

 

offset(n):跳過前面n條records

Person.count   =>3

Person.all.map {|person| "#{person.first_name} #{person.last_name" }
=> ["Joe smithson", "John Doe", "Jane smithie"] 

Person.offset(1).limit(1).map  {|person| "#{person.first_name} #{person.last_name "}
=>["John Doe"]

 

Update: 

1. 取出record,對它進行編輯而後save

2.檢索你想要編輯的record,call update method 傳新的變量的hash進去

Delete:

destory(id) 或者 destory 

從數據庫裏移除特定的instance

先實例化一個對象,而後在移除以前執行回調

delete(id)

從數據庫中刪除特定行

delete_all 

刪除全部數據

相關文章
相關標籤/搜索