![](https://prog-8.com/assets/icn_clock-e21464eeb26e89607431b51222dfc219ac4341c94a81db0219f6748b97121650.png)
2h30m Progate Ruby on Rails 5 Ⅱ(Part1)はコチラから
SNSでメインとなってくる「投稿一覧ページ」作成の続きです。
データベースを使ってみよう!
【カラム】と【レコード】
![](https://goohayami.com/wp-content/uploads/2022/03/ra22_1.png)
テーブル作成の準備
![](https://goohayami.com/wp-content/uploads/2022/03/ra22_2.png)
rails g model Post content:text
コマンドを用いて、マイグレーションファイルを作成。
![](https://goohayami.com/wp-content/uploads/2022/03/ra22_3.png)
マイグレーションエラーについて
![](https://goohayami.com/wp-content/uploads/2022/03/ra22_4-1024x409.png)
rails db:migrate
コマンド実行してマイグレーションファイルを
データベースに反映させる。
![](https://goohayami.com/wp-content/uploads/2022/03/ra22_5.png)
モデルの確認。
![](https://goohayami.com/wp-content/uploads/2022/03/ra22_6-1024x498.png)
![](https://goohayami.com/wp-content/uploads/2022/03/ra22_7.png)
Postモデルを確認する。
![](https://goohayami.com/wp-content/uploads/2022/03/ra22_8.png)
rails consoleの使い方。
![](https://goohayami.com/wp-content/uploads/2022/03/ra22_9.png)
テーブルに投稿データを保存しよう。
![](https://goohayami.com/wp-content/uploads/2022/03/ra22_10.png)
rails consoleでのコーディングになります。
post1 = post.new(content: "今日からProgateでRailsの勉強するよー!")
何度やってもエラーが出ます・・・
ここでしばらく悩んですすみませんでした。
そうです。postのpは大文字じゃなければいけません。
post1 = Post.new(content: "今日からProgateでRailsの勉強するよー!")
なんかBeautifulSoup(python)でも同じ事していたような・・・。
初心や+独学はとにかく時間がかかります。
![](https://goohayami.com/wp-content/uploads/2022/03/ra22_11-1.png)
ようやくOKが出ました。
テーブルからデータを取り出そう
![](https://goohayami.com/wp-content/uploads/2022/03/ra22_12.png)
posts = Post.all
![](https://goohayami.com/wp-content/uploads/2022/03/ra22_13.png)
posts[0] posts[1] posts[0].content posts[1].content
それぞれ取り出してみる。
rails consoleのまとめ。
![](https://goohayami.com/wp-content/uploads/2022/03/ra22_14.png)
![](https://goohayami.com/wp-content/uploads/2022/03/ra22_15.png)
最後はちょっと難しい。
indexアクション内で、@postsに代入されている配列をPost.allに書き換えてる。
![](https://goohayami.com/wp-content/uploads/2022/03/ra22_19.png)
「views/posts/index.html.erb」で投稿内容の表示部分をpost.contentを用いて書き換える。
![](https://goohayami.com/wp-content/uploads/2022/03/ra22_17.png)
ブラウザを確認すると・・・
![](https://goohayami.com/wp-content/uploads/2022/03/ra22_18.png)
post3 = Post.new(content: "やっぱりプログラミングは楽しい!") post3.save
postを追加すると
![](https://goohayami.com/wp-content/uploads/2022/03/ra22_20.png)
Rails5 Ⅱ修了まで、あと少し!