サイトイメージ
ビューページ
index.html.erb
<h1>投稿一覧</h1>
<h3>カテゴリー別投稿</h3>
<%= link_to "新規投稿へ", new_tweet_path %>
<div class="categories-container">
<% ["家庭", "閲覧注意", "会社", "友人", "学校","コメント"].each do |category| %> #ここを追加でカテゴリを増やせる
<div class="category-box">
<h2><%= category %></h2>
<div class="tweets-container">
<% @tweets.where(category: category).each do |t| %>
<div class="title">
<strong>[<%= t.category %>]</strong> <%= t.title %>
</div>
<% end %>
</div>
</div>
<% end %>
</div>
new.html.erb
<h1>新規投稿</h1>
<h3>新規投稿ページ</h3>
<%= form_for @tweet do |f| %>
<div class="field">
<%= f.label :title, "タイトル" %>
<%= f.text_field :title, size: 30 %>
</div>
<div class="field">
<%= f.label :tweet, "内容" %>
<%= f.text_area :tweet, rows: 5, cols: 30 %>
</div>
<div class="field">
<%= f.label :category, "カテゴリー" %>
<%= f.select :category, ["家庭", "学校", "閲覧注意", "会社", "友人","コメント"], prompt: "選択してください" %> #ここを追加でカテゴリを増やせる
</div>
<%= f.submit "投稿する" %>
<% end %>
<%= link_to "一覧に戻る", tweets_path %>
application.html.erb
<!DOCTYPE html>
<html>
<head>
<title>自分のタイトル</title>
<meta name="viewport" content="width=device-width,initial-scale=1">
<%= csrf_meta_tags %>
<%= csp_meta_tag %>
<%= stylesheet_link_tag "application", "data-turbo-track": "reload" %>
<%= javascript_importmap_tags %>
</head>
<body>
<%= yield %>
</body>
</html>
コントローラー
tweets_controller.rb
class TweetsController < ApplicationController
def index
@tweets = Tweet.all
end
def new
@tweet = Tweet.new
end
def create
@tweet = Tweet.new(tweet_params)
if @tweet.save
redirect_to tweets_path, notice: "投稿しました"
else
render :new
end
end
private
def tweet_params
params.require(:tweet).permit(:tweet, :category)
end
end
css
application.css
.categories-container {
display: flex;
justify-content: space-between;
gap: 20px; /* カテゴリー間の余白 */
}
.category-box {
flex: 1;
border: 2px solid #ccc;
padding: 10px;
border-radius: 8px;
background-color: #f9f9f9;
text-align: center;
}
.tweets-container {
margin-top: 10px;
}
.tweet {
padding: 5px;
border-bottom: 1px solid #ddd;
}
タグ機能よりも簡単にツイートを分類できる。
全部をカテゴリコンテナに入れているので、それ用の検索機能はまだ作ってないです