7
14

More than 3 years have passed since last update.

特定の期間の投稿数表示:今日の投稿数、今週の投稿数 scope

Posted at

やりたいこと

今日の投稿数、昨日の投稿数、前日比%
今週の投稿数、先週の投稿数、先週比を表示させたい。

モデルファイルの記述

book.rb
  scope :created_today, -> { where(created_at: Time.zone.now.all_day) } 
  scope :created_yesterday, -> { where(created_at: 1.day.ago.all_day) } 
  scope :created_this_week, -> { where(created_at: 6.day.ago.beginning_of_day..Time.zone.now.end_of_day) } 
  scope :created_last_week, -> { where(created_at: 2.week.ago.beginning_of_day..1.week.ago.end_of_day) } 

モデルファイルにスコープで記述します。こうやってモデルファイルで定義しておけば、
コントローラーもスッキリするのはわかります。

Scopeって何・・・・?

モデル側であらかじめ特定の条件式に対して名前をつけて定義し、
その名前でメソッドの様に条件式を呼び出すことが出来る仕組みのこと だそう。

コントローラーの記述

users_controller.rb
    @books = @user.books.page(params[:page]).reverse_order
    @today_book =  @books.created_today
    @yesterday_book = @books.created_yesterday
    @this_week_book = @books.created_this_week
    @last_week_book = @books.created_last_week

bookモデルに記述した定義も、usersコントローラーで使用可能!

View

 <table class="table">
  <thead>
  <tr>
   <th>今日の投稿</th>
   <th>昨日の投稿</th>
   <th>前日比</th>
  </tr>
  </thead>
   <tbody>
    <tr>
     <td><%= @today_book.count %></td>
     <td><%= @yesterday_book.count %></td>
     <% if @yesterday_book.count == 0 %>
     <td>前日の投稿はなし</td>
     <% else %>
        <td><% @the_day_before =   @today_book.count / @yesterday_book.count.to_f  %>
        <%= (@the_day_before * 100).round %>%</td>
     <% end %>
     </tr>
   </tbody>
  </table>


  <table class="table">
  <thead>
  <tr>
   <th>今週の投稿</th>
   <th>先週の投稿</th>
   <th>比</th>
  </tr>
  </thead>
   <tbody>
    <tr>
     <td><%= @this_week_book.count %></td>
     <td><%= @last_week_book.count %></td>
     <% if @last_week_book.count == 0 %>
     <td>先週の投稿はなし</td>
     <% else %>
        <td><% @the_week_before =   @this_week_book.count / @last_week_book.count.to_f  %>
        <%= (@the_week_before * 100).round %>%</td>
     <% end %>
     </tr>
   </tbody>
  </table>

難しかったのは、前日比、先週比の出し方です。
<td><% @the_week_before = @this_week_book.count / @last_week_book.count.to_f %>
 <%= (@the_week_before * 100).round %>%</td>

まず、to_fは少数点までの数値まで表示してくれるそうです。
それに100をかけて%で表示されます。

終わりに

scope使いこなせるようになりたい!!!

7
14
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
7
14