LoginSignup
0
0

More than 5 years have passed since last update.

初心者がRailsガイドを1から100まで読んでみる Railsをはじめよう編その8 データの全表示

Posted at

5.8.すべての記事を一覧表示する

記事を一つ表示できたんだから、保存されている記事全部表示することなんてちょちょいのちょいでしょ。

全部の記事を表示するページはどれにしようかなー
スクリーンショット 2018-09-16 23.04.57.png

articles#index
これが良さそう

ルートを決めてたら次にやることは
①アクションを作る
②ビューを作る
ですね(もう何回もやってきた)

articles_controller.rb
class ArticlesController < ApplicationController

    def index
        @articles = Article.all
    end

    def show
        @article = Article.find(params[:id])
    end

    def new
    end

    def create
        @article = Article.new(article_params)

        @article.save
        redirect_to @article
    end

    private
        def article_params
            params.require(:article).permit(:title, :text)
        end 
end

①コントローラにindexアクションを追加しました。
コントローラくんの仕事がだんだんわかってきたけど、モデルくんとビューくんの橋渡しみたいな感じだね。
今回はArticleモデルに保存されているすべての記事をビューに渡したいから
@articles = Article.all
と記述して、@articlesにモデルの中身を全部ぶちこんでいる。
前節で学んだけど、アクション内のインスタンス変数(@ほにゃらら)の中身は、裏でRailsちゃんが働いてて絶えずビューへコピーされる。
Article.allと書くことでArticleモデルの全レコードを抽出したことになるらしい(SQL書かないって便利)

index.html.erb
<h1>Listing articles</h1>

<table>
  <tr>
    <th>Title</th>
    <th>Text</th>
    <th></th>
  </tr>

  <% @articles.each do |article| %>
    <tr>
      <td><%= article.title %></td>
      <td><%= article.text %></td>
      <td><%= link_to 'Show', article_path(article) %></td>
    </tr>
  <% end %>
</table>

②indexビューを作りました。
前にも出てきたけど、<% ~ %>で囲まれたところにはRubyが書ける。
アクションで宣言したインスタンス変数もこの中で使用できる。

  <% @articles.each do |article| %>
    <tr>
      <td><%= article.title %></td>
      <td><%= article.text %></td>
      <td><%= link_to 'Show', article_path(article) %></td>
    </tr>
  <% end %>

今回大事なのがこの部分で、

<% @articles.each do |article| %> 
~ 
<% end %>

ここで@articlesに入っている記事に対してひとつずつ処理を行い

    <tr>
      <td><%= article.title %></td>
      <td><%= article.text %></td>
      <td><%= link_to 'Show', article_path(article) %></td>
    </tr>

そのひとつひとつの記事のタイトルとテキストと、あとその記事へのリンクを表示している。

え?
リンク?

スクリーンショット 2018-09-29 20.57.13.png
スクリーンショット 2018-09-29 20.57.51.png

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0