LoginSignup
14
9

More than 3 years have passed since last update.

CRUD機能と7つのアクションの関係性

Last updated at Posted at 2019-06-25

実装におけるそれぞれの役割

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

7つのアクションとは、Railsにおけるコントローラの基本アクションを指す。
具体的には、index、new 、create 、edit 、show 、update 、destroy の7つを指す。
詳しくわ参考記事を参照

1.Createの実装

newアクション

newアクションは、これから新しく新規投稿する時にアクションするため、定義するだけでよい。
newアクションが作動すると、新規投稿画面へと移動する。


def new
end

createアクション

新規投稿画面から 投稿した際にビューから送られる特定の情報(params,名前や文章などのこと)を受け取り、新たにDBのテーブルに送られる。


def create
    Tweet.create(image: tweet_params[:image], text: tweet_params[:text], user_id: current_user.id)
end

2.Readの実装

indexアクション 

indexアクションは、DBのあるテーブルの情報を全て取り出す。


def index
    @tweets = Tweet.includes(:user)
end

showアクション

showアクションは、indexアクションの中から、さらに個別の具体的な情報をDBのあるテーブルから取り出す。

def show
    @tweet = Tweet.find(params[:id])
    @comments = @tweet.comments.includes(:user)
end

3.Updateの実装 (Createの実装と同じ)

editアクション 

編集したい情報を指定する。

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

updateアクション

現在ログイン中のユーザーと編集したい情報のuser_idが一致すれば、updateアクションが作動する。そして、編集内容が更新される処理の流れは、createアクションと同じ

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

4.Deleteの実装

destroyアクション

updateアクションと同じ実装

5.簡易ブログアプリを作成した時のソースコード


class TweetsController < ApplicationController

  before_action :move_to_index, except: [:index, :show]

  def index
    @tweets = Tweet.includes(:user).page(params[:page]).per(5).order("created_at DESC")
  end

  def new
  end

  def create
    Tweet.create(image: tweet_params[:image], text: tweet_params[:text], user_id: current_user.id)
  end

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

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

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

  def show
    @tweet = Tweet.find(params[:id])
    @comments = @tweet.comments.includes(:user)@comments = @tweet.comments.includes(:user)@comments = @tweet.comments.includes(:user)@comments = @tweet.comments.includes(:user)
  end

  private
  def tweet_params
    params.permit(:image, :text)
  end

  def move_to_index
    redirect_to action: :index unless user_signed_in?
  end
end

<参考記事>
https://qiita.com/morikuma709/items/5b21e9853c9d6ea70295
https://qiita.com/sainu/items/9419424c68ab135472cf
https://qiita.com/aiorange19/items/d7443f403b77a7c98df0

14
9
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
14
9