SlideShare a Scribd company logo
1 of 93
Download to read offline
バカでもわかるRails #05
Model/ActiveRecord/Database 編
石井大輔 - www.jenio.co
Twitter@ishiid, email: dai@jenio.co 1
馬鹿
パパ、
Ruby on Rails教えて!
2
題名はクレージーですが、真面目な教材です
Rubyは英語みたいでとっつきやすいのに、Railsはとても難しい。
これが初心者の僕の悩みでした。もっと簡単な学習方法はないものか。
原因はRails用語が実生活で全く使わない抽象概念だからではないでしょうか。
だったらまず用語の意味を繰り返し覚えるべきでは?
英語の勉強と同じ手法を取れば良いのでは?これが僕の仮説です。
Q&A形式でクイズっぽい単語帳カードを作りましたので、
自習もしくは相方と使ってみて下さい。
コーディングを楽しみましょう! 3
単語帳の様に繰り返し学びましょう!
4
注意
この教材は一通りRailsを勉強したが、
記憶が定着していない人を対象としています。
全くの初心者の方は、
まずRubyとRailsを勉強し、補助教材として使ってください。
説明を意図的にシンプルかつ抽象的にまとめてありますので、
細かい点気になる人はググりましょう。
5
Active Recordを
勉強しよう!
6
問: ActiveRecordとは何?
7
問: ActiveRecordとは何?
8
答: リレーショナルデータベース向けのデザインパ
ターン。データを静的な行としてではなく、動的なオブ
ジェクトとして捉える。
問: ActiveRecordはどう賢いのか?
9
問: ActiveRecordはどう賢いのか?
10
答: tableの構造を理解している。tableの行のデー
タを持っている。Create/Read/Update/Deleteとい
う動きをわかっている。オブジェクトとして取り扱い、
保存が簡単。
問: ActiveRecordを使ってUserクラスにKevinを加える
コードは?
11
問: ActiveRecordを使ってUserクラスにKevinを加える
コードは?
12
答: user = User.new #空のユーザー
user.first_name = “Kevin”
user.save
問: ActiveRecordを使ってUserクラスに同様にlast
name - Smith加えるコードは?
13
問: ActiveRecordを使ってUserクラスに同様にlast
name - Smith加えるコードは?
14
答: user.last_name = “Smith”
user.save
問: 前ページのデータを消去するコード
15
問: 前ページのデータを消去するコード
16
答: user.delete
Active Relationを
勉強しよう!
17
問: ActiveRelationとは何か?略称は?
18
問: ActiveRelationとは何か?略称は?
19
答: ARel。オブジェクト指向のリレーショナル
Algebra(代数)
問: ActiveRelationは何が便利か?
20
問: ActiveRelationは何が便利か?
21
答: 複雑だったDatabase問い合わせをシンプルに
する。小さな問い合わせをつなげる。SQLを使って
問い合わせを繋げたりまとめたりできる。必要な時
のみ問合せさせればよい。
問: ActiveRelationの事例をいくつか示しなさい
22
問: ActiveRelationの事例をいくつか示しなさい
23
答: users = User.where(:first_name =>
“Kevin”)
users = users.order(“last_name ASC”).limit(5)
users = users.include(:articles_authored)
Modelを
勉強しよう!
24
問: Modelのクラス名は大文字?
25
問: Modelのクラス名は大文字?
26
答: SingularName (Camel Case)
問: Modelのファイル名は大文字?
27
問: Modelのファイル名は大文字?
28
答: singular_name.rb (Snake Case)
問: Modelを生成しなさい。単数形複数形に気をつけて。
29
問: Modelを生成しなさい。単数形複数形に気をつけて。
30
答: rails generate model SingularName (=大文
字単数形)
問: Modelはどんなファイルですか?
31
問: Modelはどんなファイルですか?
32
答: app/models/subject.rb class名:Subject 継
承:ActiveRecord ファイル名、クラス名、table名に
注意
問: app/models/user.rbの中身は?
33
問: app/models/user.rbの中身は?
34
答: class User < ActiveRecord::Base
self.table_name = “admin_users”
end
問: admin_user.rbモデルのコードの骨格は?
35
問: admin_user.rbモデルのコードの骨格は?
36
答: class User < ActiveRecord::Base
end
問: 前ページの続きで、first_name, last_nameにアクセ
スするコードは?
37
問: 前ページの続きで、first_name, last_nameにアクセ
スするコードは?
38
答: attr_accessor :first_name
attr_accessor :last_name
Rails Consoleを
勉強しよう!
39
問: irbとは?
40
問: irbとは?
41
答: interactive ruby。Rubyの簡易入力形式。
問: consoleでsubjectというvalueを作ってください
42
問: consoleでsubjectというvalueを作ってください
43
答: subject = Subject.new (空のデータ)
問: consoleでsubjectにKevinというvalueを代入して下
さい
44
問: consoleでsubjectにKevinというvalueを代入して下
さい
45
答: subject.name = “Kevin”
問: consoleでKevinを表示させて下さい
46
問: consoleでKevinを表示させて下さい
47
答: subject.name
問: 本番環境のconsoleを立ち上げてください
48
問: 本番環境のconsoleを立ち上げてください
49
答: rails console production
問: consoleでいうNew/Saveとはどんな作業ですか?
50
問: consoleでいうNew/Saveとはどんな作業ですか?
51
答: オブジェクトのインスタンス化>Valueの設定>保
存
問: 前ページの作業をsubjectとコードで表現してください
52
問: 前ページの作業をsubjectとコードで表現してください
53
答: subject = Subject.new (インスタンス化)
subject.new_record? >> true(保存前)
subject.name = “First Subject”
subject.save >>> true (保存終了)
subject.id >>> 1
問: consoleでいうCreateとはどんな作業ですか?
54
問: consoleでいうCreateとはどんな作業ですか?
55
答: オブジェクトのインスタンス化+Valueの設定+保
存を一度にやる事
問: 前ページの作業をsubjectとコードで表現してください
56
問: 前ページの作業をsubjectとコードで表現してください
57
答: subject = Subject.create( : name =>
“Second Subject”, :position => “2” )
subject (保存済)
問: consoleでいうFind/Saveとはどんな作業ですか?
58
問: consoleでいうFind/Saveとはどんな作業ですか?
59
答: 記録を見つける>>Valueの設定>>保存する
問: 前ページの作業をsubjectとコードで表現してください
60
問: 前ページの作業をsubjectとコードで表現してください
61
答: subject.new_record? >> false(保存済)
subject.name = “Initial Subject”(上書き)
subject.save >>> true (保存終了)
subject >>> “Initial Subject”
問: consoleでいうFind/update_attributeとはどんな作業
ですか?
62
問: consoleでいうFind/update_attributeとはどんな作業
ですか?
63
答: 記録を見つける>>Valueの設定+保存するを
一度にやる
問: 前ページの作業をsubjectとコードで表現してください
64
問: 前ページの作業をsubjectとコードで表現してください
65
答: subject = Subject.find(2)
subject.update_attributes( :name=> “Next
Subject”, :visible => true )
問: consoleでいうdelete/destroyはどっちが正しい?
66
問: consoleでいうdelete/destroyはどっちが正しい?
67
答: 厳密にはdestroyを使うべき。deleteは推薦しな
い。
問: consoleでいうFind/destroyとはどんな作業ですか?
68
問: consoleでいうFind/destroyとはどんな作業ですか?
69
答: 記録を見つける>>データを破壊する
問: bad subjectを3番目のデータとして作って、破壊してく
ださい
70
問: bad subjectを3番目のデータとして作って、破壊してく
ださい
71
答: subject.create(:name => “Bad Subject”)
subject = Subject.find(3)
subject.destroy (not delete!)
subject >> nil
Databaseを
組み立てよう!
72
問: 新しいDatabaseを組み立てる順番は?
73
問: 新しいDatabaseを組み立てる順番は?
74
答: migration >> model
(has_many/belongs_to) >> controller >> view
問: Migrationでデータを積み直すコマンドは?
75
問: Migrationでデータを積み直すコマンドは?
76
答: reload!
問: blogpostに最初の値を代入してください
77
問: blogpostに最初の値を代入してください
78
答: blogpost = Blogpost.first
問: 前ページのblogpostにcommentデータを追加してくだ
さい
79
問: 前ページのblogpostにcommentデータを追加してくだ
さい
80
答: blogpost.comments.build (空データ)
blogpost.comments.save (保存)
問: bにそれぞれの@blogpostを実行し代入するコードは
何?
81
問: bにそれぞれの@blogpostを実行し代入するコードは
何?
82
答: <% @blogpost.each do |b| %>
問:blogpostに付随したcommentを入力するフォームの
コードは何?
83
問:blogpostに付随したcommentを入力するフォームの
コードは何?
84
答: <%= form_for [blogpost, blogpost.
comments.build] do |c| %>
問:blogpostsに付随したcomments Databaseを参照す
るためのroutes.rbは何?
85
問:blogpostsに付随したcomments Databaseを参照す
るためのroutes.rbは何?
86
答: resources :blogposts do
resources :comments
end
問:createメソッド中で、json形式でパラメーターを表示さ
せて下さい
87
問:createメソッド中で、json形式でパラメーターを表示さ
せて下さい
88
答: def create
return render json: params
end
問:migrationの列の項目が間違っていた時の修正方法
89
問:migrationの列の項目が間違っていた時の修正方法
90
答: a) rake db:rollback >> rake db:migrate
b) reload! コマンド
問:comments tableのbody列のデータを取得するコード
91
問:comments tableのbody列のデータを取得するコード
92
答: params[:comment][:body] >>> return
“nice post”
GOAL! よくできました!
良かったら繰り返しチャレンジしてみてください。
93
改善の為の、
ご意見ご感想お待ちしています。
Twitter@ishiid
https://twitter.com/ishiid
Email: dai@jenio.co

More Related Content

Recently uploaded

Recently uploaded (7)

NewSQLの可用性構成パターン(OCHaCafe Season 8 #4 発表資料)
NewSQLの可用性構成パターン(OCHaCafe Season 8 #4 発表資料)NewSQLの可用性構成パターン(OCHaCafe Season 8 #4 発表資料)
NewSQLの可用性構成パターン(OCHaCafe Season 8 #4 発表資料)
 
Amazon SES を勉強してみる その22024/04/26の勉強会で発表されたものです。
Amazon SES を勉強してみる その22024/04/26の勉強会で発表されたものです。Amazon SES を勉強してみる その22024/04/26の勉強会で発表されたものです。
Amazon SES を勉強してみる その22024/04/26の勉強会で発表されたものです。
 
業務で生成AIを活用したい人のための生成AI入門講座(社外公開版:キンドリルジャパン社内勉強会:2024年4月発表)
業務で生成AIを活用したい人のための生成AI入門講座(社外公開版:キンドリルジャパン社内勉強会:2024年4月発表)業務で生成AIを活用したい人のための生成AI入門講座(社外公開版:キンドリルジャパン社内勉強会:2024年4月発表)
業務で生成AIを活用したい人のための生成AI入門講座(社外公開版:キンドリルジャパン社内勉強会:2024年4月発表)
 
Amazon SES を勉強してみる その32024/04/26の勉強会で発表されたものです。
Amazon SES を勉強してみる その32024/04/26の勉強会で発表されたものです。Amazon SES を勉強してみる その32024/04/26の勉強会で発表されたものです。
Amazon SES を勉強してみる その32024/04/26の勉強会で発表されたものです。
 
LoRaWAN スマート距離検出デバイスDS20L日本語マニュアル
LoRaWAN スマート距離検出デバイスDS20L日本語マニュアルLoRaWAN スマート距離検出デバイスDS20L日本語マニュアル
LoRaWAN スマート距離検出デバイスDS20L日本語マニュアル
 
新人研修 後半 2024/04/26の勉強会で発表されたものです。
新人研修 後半        2024/04/26の勉強会で発表されたものです。新人研修 後半        2024/04/26の勉強会で発表されたものです。
新人研修 後半 2024/04/26の勉強会で発表されたものです。
 
LoRaWANスマート距離検出センサー DS20L カタログ LiDARデバイス
LoRaWANスマート距離検出センサー  DS20L  カタログ  LiDARデバイスLoRaWANスマート距離検出センサー  DS20L  カタログ  LiDARデバイス
LoRaWANスマート距離検出センサー DS20L カタログ LiDARデバイス
 

Featured

How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental Health
ThinkNow
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
Kurio // The Social Media Age(ncy)
 

Featured (20)

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPT
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage Engineerings
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental Health
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
 
Skeleton Culture Code
Skeleton Culture CodeSkeleton Culture Code
Skeleton Culture Code
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
 

バカでもわかるRails #05