1
0

More than 3 years have passed since last update.

【Rails】複数モデルの作成日付一覧を重複なく表示する

Posted at
1 / 2

ポートフォリオ作成中の学びのアウトプットとして投稿させて頂きます。
勉強用アプリを作成中に実装した保存された回答(複数モデル存在)を日付順に重複なく表示する方法です。

実現したいこと

users_controllerのshowアクションで回答の作成日付一覧をviewに表示してそれぞれの日付をクリックするとその日に作成された回答一覧を確認できるようにしたい。
※下図のイメージ
2021-09-11 1.17.47.png

モデル

回答用モデルとして「answer」と「reaction」が存在。

showアクションとviewの中身

users_controller.rb
 def show
    @answers_dates = current_user.answers.map{|dates| dates.created_at.to_date}
    @reactions_dates = current_user.reactions.map{|dates| dates.created_at.to_date}
    @dates = @answers_dates.push(@reactions_dates).flatten.uniq.sort.reverse
  end
show.html.erb
  <% @dates.each do |record| %>
      <li>
       <%= link_to record, answers_path(created_at: record) %>
   </li>
  <% end %>

中身の説明

@answers_dates = current_user.answers.map{|dates| dates.created_at.to_date}
@reactions_dates = current_user.reactions.map{|dates| dates.created_at.to_date}

全てのanswer及びreactionをインスタンス変数に配列として保存する。同時に年月日だけ表示されれば良いのでto_dateメソッドを用いて変換。

@dates = @answers_dates.push(@reactions_dates).flatten.uniq.sort.reverse

二つの配列をpushメソッドで結合。結合すると配列が入れ子構造になるので(ex,[2021-09-08, [2021-09-08,2021-09-09]])、flattenメソッドで入れ子構造を外す。uniqメソッドで重複を除去、さらにsort.reverseで日付が近い順に並び替える。
※入れ子構造を外さないとuniqで上記の例だと2021-09-08の重複を除去できない。

 <% @dates.each do |record| %>
      <li>
       <%= link_to record, answers_path(created_at: record) %>
   </li>
  <% end %>

後は表示される日付にリンクを付属し、その日付をparamsとしてパスに与えることでその日付に作成されたモデルを取り出せる。

1
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
1
0