LoginSignup
3
2

More than 3 years have passed since last update.

Railsを使ったToDoリストの作成(6.CRUDのUpdate機能)

Posted at

概要

本記事は、初学者がRailsを使ってToDoリストを作成する過程を記したものです。
私と同じく初学者の方で、Railsのアウトプット段階でつまづいている方に向けて基礎の基礎を押さえた解説をしております。
抜け漏れや説明不足など多々あるとは思いますが、読んでくださった方にとって少しでも役に立つ記事であれば幸いです。

環境

  • Homebrew: 2.5.10 -> MacOSのパッケージ管理ツール
  • ruby: 2.6.5p114 -> Ruby
  • Rails: 6.0.3.4 -> Rails
  • node: 14.3.0 -> Node.js
  • yarn: 1.22.10 -> JSのパッケージ管理ツール
  • Bundler: 2.1.4 -> gemのバージョン管理ツール
iTerm
$ brew -v => Homebrew 2.5.10
$ ruby -v => ruby 2.6.5p114
$ rails -v => Rails 6.0.3.4
$ npm version => node: '14.3.0'
$ yarn -v => 1.22.10
$ Bundler -v => Bundler version 2.1.4

第6章 CRUDのUpdate(edit/update)

第6章では、以下の機能を実装していきます。

  • 編集画面(editアクション)
  • 編集画面で入力された情報をデータベースに保存する機能(updateアクション)

では、詳しく見ていきましょう。

1 editアクション

まずは、editアクションを使って編集画面を実装していきます。
一覧表示画面から編集ボタンを押したら、編集画面に遷移できるようにしたいと思います。

1 コントローラ

コントローラには以下のように記述します。

app/controllers/boards_controller.rb
def edit
    @board = Board.find(params[:id])
end

editアクションでは、登録済みのフォーム画面を予め表示できるように、URLに含まれているタスクのidをパラメータから受け取り、それを使ってデータベースから対象のオブジェクトを取得します。

2 ビュー

ビューでは、まず編集フォームを作成します。
フォームはnew.html.hamlで作成したものとほぼ同じ内容です。

app/views/edit.html.haml
.container
  %h2.form_title Edit Board
  = form_with(model: @board, local: 'true') do |f|
    %div
      = f.label :title, 'Name'
    %div
      = f.text_field :name, class: 'text'
    - if @board.errors.include?(:name)
      %p.error=@board.errors.full_messages_for(:name).first
    %div
      = f.label :description, 'Description'
    %div
      = f.text_area :description, class: 'text'
    - if @board.errors.include?(:description)
      %p.error=@board.errors.full_messages_for(:description).first
    %div
      = f.submit :Submit, class: 'btn-primary'

次に、一覧表示画面に編集画面へ遷移することができるようリンクを貼ります。

app/views/index.html.haml
= link_to 'Edit', edit_board_path(board)

以上で、編集画面の実装は終了です。

2 updateアクション

編集画面から入力されたデータを使ってデータベースを更新するためにupdateアクションを実装していきます。

コントローラ

コントローラに以下のように記述します。

app/controllers/boards_controller.rb
def update
    @board = Board.find(params[:id])
    if @board.update(board_params)
        redirect_to board_path(@board), notice: 'Update successful'
    else
        flash.now[:error] = 'Could not update'
        render :edit
    end
end

Board.findで更新したいboardを取得します。
ActiveRecordのupdateメソッドを実行し、編集したインスタンスをデータベース保存します。

editアクションとupdateアクションの内容や関係性は、新規登録機能のnewアクションとcreateアクションに似ているため、Createの記事を参考にしてください。

以上で、編集機能の実装は完了です。

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