LoginSignup
8
11

More than 3 years have passed since last update.

【Ruby on Rails】投稿の編集機能(更新、削除)

Last updated at Posted at 2020-09-03

目標

  • 編集、更新
    編集.gif

  • 削除
    削除.gif

開発環境

ruby 2.5.7
Rails 5.2.4.3
OS: macOS Catalina

前提

1,ルーティングの変更

config/routes.rb
resources :posts, only: [:create, :new]

上記記述に下記を追加することで、edit,update,destroy のルート設定。

config/routes.rb
resources :posts, only: [:create, :new, :edit, :update, :destroy]

下記の結果になればOKです。

ターミナル
$ rails routes

...

posts     POST     /posts(.:format)           posts#create
new_post  GET      /posts/new(.:format)       posts#new
edit_post GET      /posts/:id/edit(.:format)  posts#edit
post      PATCH    /posts/:id(.:format)       posts#update
          PUT      /posts/:id(.:format)       posts#update
          DELETE   /posts/:id(.:format)       posts#destroy

2,コントローラーの変更

下記を追加

app/controllers/posts_controller.rb

...

  def edit
   @post = Post.find(params[:id])
  end

  def update
    @post = Post.find(params[:id])
    if @post.update(post_params)
      redirect_to request.referer
    else
      render :new
    end
  end

  def destroy
    @post = Post.find(params[:id])
    @post.destroy
    redirect_to request.referer
  end

3,ビューの変更

app/views/posts 配下にedit.html.erb ファイルを新規作成

app/views/posts/edit.html.erb
<h1>Posts#edit</h1>
<span>現在ログイン中のユーザー:<%= current_user.name %></span>
<%= form_for(@post, url: post_path(@post)) do |f| %>
    <div>
        <%= f.label :タイトル %><br>
        <%= f.text_field :title, autofocus: true, :placeholder =>"#{@post.title}" %>
    </div>
    <div>
        <%= f.label :中身 %><br>
        <%= f.text_area :body, :placeholder =>"#{@post.body}" %>
    </div>
    <div><%= f.submit "更新する" %></div>
<% end %>
app/views/posts/new.html.erb
<table>
    <thead>
        <tr>
            <th>投稿者名</th>
            <th>タイトル</th>
            <th>本文</th>
        </tr>
    </thead>
    <tbody>
        <% @posts.each do |post| %>
            <tr>
                <td><%= post.user.name %></td>
                <td><%= post.title %></td>
                <td><%= post.body %></td>
                <td><%= link_to "編集", edit_post_path(post) %></td>         ←追加
                <td><%= link_to "削除", post_path(post), method: :delete %></td>  ←追加
            </tr>
        <% end %>
    </tbody>
</table>
8
11
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
8
11