AR삽질러

初めてのRuby on Rails ミニQ&Aサイト開発 - delete, destroy 削除(5) 본문

Ruby/RubyOnRails-日本語

初めてのRuby on Rails ミニQ&Aサイト開発 - delete, destroy 削除(5)

아랑팡팡 2024. 1. 4. 16:06
728x90

 

初めてのRuby on Rails ミニQ&Aサイト開発 - delete, destroy 削除(5)

 

questions_controller.rb

class QuestionsController < ApplicationController
	# 質問の削除
    def destroy
        @question = Question.find(params[:id])
        @question.destroy
        redirect_to questions_path
    end
end

 - destroyアクションはURLから受けた 'params[:id]' を使って削除する質問す探す。

 - @question.destroyを呼び出して質問をDataBaseから削除する。

 - 削除して後、ユーザーを質問List Pageにリダイレクトする( redirect_to questions_path )

 

index.html.erb

<h1>Questions</h1>

<table>
    <tr>
        <th>ID</th>
        <th>Title</th>
        <th>Name</th>
        <th>Content</th>
    </tr>
    <% @questions.each do |question| %>
        <tr>
            <td><%= question.id %></td>
            <td><%= question.title %></td>
            <td><%= question.name %></td>
            <td><%= question.content %></td>
            <td><%= link_to 'show', question_path(question) %></td>
            <td><%= link_to 'edit', edit_question_path(question) %></td>
            <td><%= link_to 'destroy', question_path(question),
            data: { turbo_method: 'delete', turbo_confirm: 'Are you sure?' }%></td>
        </tr>
    <% end %>
</table>

link_to 'destroy'

 - 各質問に対する destroyリンクを生成する。

question_path(question)

 - 質問の削除URLを提供する。

date: { turbo_method: 'delete', turbo_confim: 'Are you sure?' }

 - 削除要請の時、Turbo Driveを使ってHTTP 'DELETE'を送って、ユーザーの削除確認メッセージ表紙する。

 

index.html.erb


Viewのリファクタリング

 - フォームを再利用できる部分(partial)に分離してコードの重複を減らしメンテナンスを容易にする戦略を使用

 

_form.html.erb

<!-- app/view/question/_form.html.erb -->
<%= form_with model: @question do |form| %>
    <% if @question.errors.any? %>
    <div>
        <ul>
            <% @question.errors.full_messages.each do |message| %>
                <li><%= message %></li>
            <% end %>
        </ul>
    </div>
    <% end %>
    <div>
        <%= form.label :title %>
        <%= form.text_field :title %><br><br>
    </div>
    <div>
        <%= form.label :name %>
        <%= form.text_field :name %><br><br>
    </div>
    <div>
        <%= form.label :content %>
        <%= form.text_area :content %>
    </div>
    <div>
        <%= form.submit %>
    </div>
<% end %>

 

 

new.html.erb

<h1>New Question</h1>
<%= render partial: 'form' %>

render partial: 'form'

 -  new ViewでFormを直接作成する代わりに、_formを再利用する。

 


 

https://github.com/designAR/rails_board/tree/destroy_%2305

 

GitHub - designAR/rails_board

Contribute to designAR/rails_board development by creating an account on GitHub.

github.com

 

 

 

 

728x90
반응형
LIST