2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【超簡単】Rails 日ごとに投稿をまとめ詳細ページに表示する

Last updated at Posted at 2022-10-16

はじめに

日ごとに投稿を1つのリンクにまとめ、その遷移先にその日の投稿がまとまったページを作成する方法を伝授します!
コピペだけで実装できます!
(※実装しているものと若干合わせる必要はあると思います🙏)

コントローラー

posts_controller.rb

class TweetsController < ApplicationController
  def index
    @tweet = Tweet.new
    @days = Tweet.group("date(created_at)")
  end

  def create
    tweet = Tweet.new(tweet_params)
    if tweet.save
      redirect_to :action => "index"
    else
      redirect_to :action => "index"
    end
  end

  def show
    @date = params[:date]
    @tweets = Tweet.where("created_at LIKE ? ",'%' + params[:date] + '%')
  end

  private
  def tweet_params
    params.require(:tweet).permit(:body)
  end

end

ルート

routes.rb
  root "tweets#index"
  post 'tweets' => 'tweets#create'
  get 'tweets/:date' => 'tweets#show',as: 'tweet'

ビュー

index.html.erb
<h1>投稿する</h1>
<%= form_for @tweet do |f| %>
  <div class="field">
    <%= f.label :body %>
    <%= f.text_field :body, :size => 140 %>
  </div>
  <%= f.submit "Tweetする" %>
<% end %>

<h1>日付一覧</h1>
<div class="tweets-container">
  <% @days.each do |t| %>
      <a  href="/tweets/<%= t.created_at.to_date %>"><%= t.created_at.to_date %></a><br>
  <% end %>
</div>
show.html.erb

<h1><%= @date %>の投稿</h1>

<% @tweets.each do |t| %>
  <div class="tweet">
    <%= t.body %>
  </div>
<% end %>

最後に

いかがでしたでしょうか?
解説は余力があれば追記していこうと思います!
そのほか何かありましたら気軽になんでもコメントいただければと思います!

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?