LoginSignup
0
0

More than 1 year has passed since last update.

記事投稿の「タイトル」を作りたいよ〜投稿内容に加えて

Posted at

はじめに

SNS風のWEBアプリを元に、記事投稿サイトにしていきたい。
SNSだとタイトルは必要ないため、内容のみの実装していた。
そこで、投稿にタイトルを追加し、投稿内容と一緒にタイトルをつけてタイムラインに表示させるようにする。

No 項目 内容
1 OS Mac
2 Ruby 2.6.3
3 rails 6.0.4

カラムの追加

contentカラムのみ実装されていたので、titleカラムを追加する。
rails generate migration "Add「カラム名」To「モデル名」 カラム名:データ型
の順で投げるとchangeメソッドの中に自動でadd_columnを生成してくれる。

ターミナル
$ rails generate migration AddTitleToMicroposts title:string
db/migrate/20220624154740_add_title_to_microposts.rb
class AddTitleToMicroposts < ActiveRecord::Migration[6.0]
  def change
    add_column :microposts, :title, :string
  end
end

新規投稿ページにtitle入力フォームの追加

form_withの中にtitleを入力するフォームを追加する。
タイトルを入力し、Postリクエストが発行されると、params[micropost][title]に格納され、createコントローラに渡される。

new.html.erb
<%= form_with(model: @micropost, local: true) do |f| %>
  <%= render 'shared/error_messages', object: f.object %>
  <div class="field">
# ここに追加
    <%= f.label :title, '投稿タイトル' %>
    <%= f.text_field :title, class: 'form-control' %>
    
        <%= f.label :content, '投稿文' %>
    <%= f.text_area :content %>
  </div>
  <%= f.submit "Post", class: "btn btn-primary" %>
<% end %>

Controllerのストロングパラメータに:titleを追加

前述した通り、params[micropost][title]をcreateアクションで受け取る。
その際に、ストロングパラメータによって書き換えるパラメータを限定することによって、admin情報の書き換え等の対策をする。修正前は:contentに対してのみpermitしていたため、:titleを追加する。

micropost_controller.html.rb
    # アクションは特に変えない(micropost_paramsの内容に修正を加える)
  def create 
    @micropost = current_user.microposts.build(micropost_params)
    if @micropost.save
      flash[:success] = "Micropost created!"
      redirect_to root_url
    else
      @feed_items = current_user.feed.paginate(page: params[:page])
      render 'microposts/new'
      # redirect_to root_url
    end
  end
.
.
.
   # strong parameter
    def micropost_params
    # permitに:titleキーを渡す
      self.params.require(:micropost).permit(:content, :title)
      # params[:micropost][:content/:title] 
    end

一覧に表示する

今回はタイトルをクリックすると、その投稿のshowテンプレートのリンクに飛ぶようにする。

index.html.erb
    <span class="post-title">
      <%= link_to micropost.title, micropost_url(micropost.id) %>
    </span>

CSSを整える

custom.scss
.post-title {
    font-weight: bold;
    display: block;
    margin-left: 60px;
    color: inherit;
    text-decoration: none;
  }

Modelsでvalidationをかける

micropost.rb
  validates :title, presence: true, length: { maximum: 50 }

終わりに

鯖缶はうまい。
IMG20220625122953.jpg

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