0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

CRUD機能のU(Update)におけるデータベース間とのやりとり

Posted at

CRUD機能とは、ほぼ全てのソフトウェアが有する4つの永続的な基本機能の頭文字をそれぞれ並べた用語のことをいう。 その4つの機能とは、Create(生成)、Read(読み取り)、Update(更新)、Delete(削除)を指す。

今回は、UのUpdateについての仕組みを解説する。そのため、主にコントローラのeditアクションとupdateアクションについて解説する。Updateは、既にデータベースに存在するデータを新たに更新することである。Update処理の流れとしては、editアクション→updateアクションの順番となる。

1.Updateの処理の流れ

データベース上既に存在する特定のデータを抽出する処理(editアクション)
     ↓
抽出したデータを更新し、再びデータベースに保存する処理(updateアクション)

2.データベース上既に存在する特定のデータを抽出する処理(editアクション)

データを更新するためには、編集画面に移動する必要がある。

ルーティングを設定する。


get   'tweets/:id/edit'  => 'tweets#edit'

コントローラを設定する


def edit
    @tweet = Tweet.find(params[:id])
end

editアクションは、データベースの特定のテーブルから,編集したいレコード(ここでは、ツイートのid)を抽出する。そして、そのデータを編集画面のビューに送る。

3.抽出したデータを更新し、再びデータベースに保存する処理(updateアクション)

editアクションによって呼び出された編集画面に新規投稿する。その際、ビューの方であらかじめ、ルーティングが呼び出される記述をする。(今回は、form_tagを使う。)

<%= form_tag("/tweets/#{@tweet.id}", method: :patch ) do %>

これにより、編集をして新規投稿した時にルーティングが呼びだされる。ちなみに、編集をする際に使用するhttpメソッドはpatchである。

ルーティングの設定


patch   'tweets/:id'  => 'tweets#update'

これにより、新規投稿した時にコントローラのupdateアクションが実行するようになる。

コントローラの設定


  def update
    tweet = Tweet.find(params[:id])
    if tweet.user_id == current_user.id
      tweet.update(tweet_params)
    end
  end

updateアクションは、編集するデータがログイン中のユーザーであれば、編集されたデータを新規投稿を行い、テーブルに新たなレコードを保存するようになる(データベースとのやりとりにおいては、createアクションと同じ動きをする。)

ちなみに、if文を1行に省略して記述する方法として、後置ifを用いて記述する方法がある。

def update
    tweet = Tweet.find(params[:id])
    tweet.update(tweet_params) if tweet.user_id == current_user.id
end
0
0
4

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?