いわりょのBlog

IT関連で学んだことを書いていきます。

TOPページでArticleモデルから更新順3件の記事を表示。

実現するもの

f:id:Ryo10Leo:20200103151425p:plain
HPのトップページで最新記事3件がよくあります。
Articleモデルから3件の記事を更新順に抽出して表示していきます。

f:id:Ryo10Leo:20200107141146p:plain
使っているArticleモデルはこんな感じ。
content、記事の内容についてはHTML文を保存しています。

home.html.erb

<% if  @top_news %>
<div id="top-news-container">
    <h2 class="page-title">News</h2>
    <article id="top-posts">
    <% @top_news.each do |article| %>
            <div class="news">
                <%= link_to article_path(article) do %>
                    <%== article_thumb(article.content) %>
                <% end %>
                <p class="news-date"><%= l article.created_at %></p>
                <h1><%= article.title %></h1>
                <p class="news-text"><%= article_content(article) %></p>
                <div class="top-news-btn"><%= link_to 'Read More', article_path(article) %></div>
            </div>
    <% end %>
    </article><!--top-posts-->
</div><!--top-news-container-->
<% end %>

記事のテンプレートはこんな感じ。複数表示するためにeachを使っていることに注目。デザインは省略します。

<%== article_thumb(article.content) %>は、サムネイルを表示させるためにヘルパーメソッドです。下記の記事で解説してます。

ryo10leo.hatenablog.com

<%= l article.created_at %>は日付のフォーマットを指定して表示させています。↓
ryo10leo.hatenablog.com

<%= article_content(article) %>は記事の概要ですね↓
ryo10leo.hatenablog.com

テンプレートができたら記事をコントローラーから3件だけ抽出していきます。
が、可読性を上げたいのでArticleモデルのファイルにスコープを定義した方が良さそうです。

article.rb

class Article < ApplicationRecord
  scope :recent_news, -> { order(id: :desc).limit(3) }
end

これでArticle.recent_newsとかけば、新しい方から3件記事が抽出されます。

あとはコントローラーに追記。

home_controller.rb

class HomeController < ApplicationController

  include StaticPagesHelper

  def home
    @top_news = Article.recent_news
  end

end

これで完了!