《Rails-Guides》Reading notes one:Active Record Basics

Preface

????????These are the new guides for Rails 5.1 based on?v5.1.6.?These guides are designed to make you immediately productive with Rails, and to help you understand how all of the pieces fit together.

What is Active Record?

????????Active Record is the M in MVC.?the model - which is the layer of the system responsible for representing business data and logic. Active Record facilitates the creation and use of business objects whose data requires persistent storage to a database. It is an implementation of the Active Record pattern which itself is a description of an Object Relational Mapping system.

? ? ? ?Active Record gives us several mechanisms, the most important being the ability to:1.Represent models and their data.2.Represent associations between these models.3.Represent inheritance hierarchies through related models.4.Validate models before they get persisted to the database.5. Perform database operations in an object-oriented fashion.

Convention over Configuration in Active Record

????????When writing applications using other programming languages or frameworks, it may be necessary to write a lot of configuration code. This is particularly true for ORM frameworks in general. However, if you follow the conventions adopted by Rails, you'll need to write very little configuration (in some cases no configuration at all) when creating Active Record models. The idea is that if you configure your applications in the very same way most of the time then this should be the default way. Thus, explicit configuration would be needed only in those cases where you can't follow the standard convention.

Naming Conventions

????????By default, Active Record uses some naming conventions to find out how the mapping between models and database tables should be created. Rails will pluralize your class names to find the respective database table. So, for a class?Book, you should have a database table called?books. When using class names composed of two or more words, the model class name should follow the Ruby conventions, using the CamelCase form.

Schema Conventions

? ??????Primary keys?- By default, Active Record will use an integer column named?id?as the table's primary key. When using Active Record Migrations?to create your tables, this column will be automatically created.

? ??????Foreign keys?- e.g.,?item_id,?order_id

Creating Active Record Models

????????class Product < ApplicationRecord

????????????????CREATE TABLE products (

???????????????????????id? int(11)? NOT NULL auto_increment,

???????????????????????name varchar(255),

???????????????????????PRIMARY? KEY? (id)

????????????????);

????????end

????????p = Product.new

????????p.name = "Some Book"

????????puts p.name ---- # "Some Book"

Overriding the Naming Conventions

? ? ? ?1. use your Rails application with a legacy database

????????????????class Product < ApplicationRecord

??????????????????????????self.table_name = "my_products"

? ? ? ? ? ? ? ? ?end

? ? ? ?2. used as the table's primary key using the?ActiveRecord::Base.primary_key

????????????????classProduct < ApplicationRecord

??????????????????????self.primary_key = "product_id"

????????????????end

CRUD: Reading and Writing Data

????????CRUD is an acronym for the four verbs we use to operate on data:?Create,?Read,?Update and?Delete.?

1 Create

? ???????The?new?method will return a new object while?create?will return the object and save it to the database.

? ? ? ? ?①user = User.create(name: "David", occupation: "Code Artist")

? ? ? ? ?②user = User.new

????????????user.name = "David"

????????????user.occupation = "Code Artist"

? ? ? ? ? ? user.save

2 Read

3 Update

4 Delete

Validations

????????Active Record allows you to validate the state of a model before it gets written into the database.?

Callbacks

????????Active Record callbacks allow you to attach code to certain events in the life-cycle of your models. This enables you to add behavior to your models by transparently executing code when those events occur, like when you create a new record, update it, destroy it and so on.

Migrations

????????Rails provides a domain-specific language for managing a database schema called migrations. Migrations are stored in files which are executed against any database that Active Record supports using?rake. Here's a migration that creates a table:

????????Rails keeps track of which files have been committed to the database and provides rollback features. To actually create the table, you'd run?rails db:migrate?and to roll it back,?rails db:rollback.

????????Note that the above code is database-agnostic: it will run in MySQL, PostgreSQL, Oracle and others.?








user = User.create(name: "David", occupation: "Code Artist")

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
  • 序言:七十年代末靶橱,一起剝皮案震驚了整個濱河市溯饵,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌盆顾,老刑警劉巖,帶你破解...
    沈念sama閱讀 211,265評論 6 490
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件嘲玫,死亡現(xiàn)場離奇詭異僧鲁,居然都是意外死亡,警方通過查閱死者的電腦和手機牧氮,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,078評論 2 385
  • 文/潘曉璐 我一進店門琼腔,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人踱葛,你說我怎么就攤上這事丹莲。” “怎么了尸诽?”我有些...
    開封第一講書人閱讀 156,852評論 0 347
  • 文/不壞的土叔 我叫張陵甥材,是天一觀的道長。 經常有香客問我性含,道長洲赵,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 56,408評論 1 283
  • 正文 為了忘掉前任,我火速辦了婚禮叠萍,結果婚禮上芝发,老公的妹妹穿的比我還像新娘。我一直安慰自己苛谷,他們只是感情好后德,可當我...
    茶點故事閱讀 65,445評論 5 384
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著抄腔,像睡著了一般瓢湃。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上赫蛇,一...
    開封第一講書人閱讀 49,772評論 1 290
  • 那天绵患,我揣著相機與錄音,去河邊找鬼悟耘。 笑死落蝙,一個胖子當著我的面吹牛,可吹牛的內容都是我干的暂幼。 我是一名探鬼主播筏勒,決...
    沈念sama閱讀 38,921評論 3 406
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼旺嬉!你這毒婦竟也來了管行?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 37,688評論 0 266
  • 序言:老撾萬榮一對情侶失蹤邪媳,失蹤者是張志新(化名)和其女友劉穎捐顷,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體雨效,經...
    沈念sama閱讀 44,130評論 1 303
  • 正文 獨居荒郊野嶺守林人離奇死亡迅涮,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 36,467評論 2 325
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了徽龟。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片叮姑。...
    茶點故事閱讀 38,617評論 1 340
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖据悔,靈堂內的尸體忽然破棺而出传透,到底是詐尸還是另有隱情,我是刑警寧澤屠尊,帶...
    沈念sama閱讀 34,276評論 4 329
  • 正文 年R本政府宣布旷祸,位于F島的核電站,受9級特大地震影響讼昆,放射性物質發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 39,882評論 3 312
  • 文/蒙蒙 一浸赫、第九天 我趴在偏房一處隱蔽的房頂上張望闰围。 院中可真熱鬧,春花似錦既峡、人聲如沸羡榴。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,740評論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽校仑。三九已至,卻和暖如春传惠,著一層夾襖步出監(jiān)牢的瞬間迄沫,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 31,967評論 1 265
  • 我被黑心中介騙來泰國打工卦方, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留羊瘩,地道東北人。 一個月前我還...
    沈念sama閱讀 46,315評論 2 360
  • 正文 我出身青樓盼砍,卻偏偏與公主長得像尘吗,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子浇坐,可洞房花燭夜當晚...
    茶點故事閱讀 43,486評論 2 348

推薦閱讀更多精彩內容