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?

アクションコントローラーについて

Posted at

はじめに

Railsのアクションコントローラーについて学んだので、アウトプットしてみたいと思います。

index

一覧表示をするページやトップページで使います。

castle_controller.rb
def index
 @castle = Castle.all
end

@castleはインスタンス変数に該当します。インスタンス変数は同一のインスタンス内で使用できる変数のことで、メソッド内に設定すると、対応するビュー間とでデータをやり取りできます。

Castleはローカル変数に該当します。ローカル変数は定義されたメソッド内でのデータのやり取りでしか使用できない関数です。

show

詳細ページを表示する時に使います。

castle_controller.rb
def show
 @castle = Castle.find(params[:id])
end

idに対応するデータを表示します。

new

新規でインスタンスを作成し、表示する時に使う。

castle_controller.rb
def new
 @castle = Castle.new
end

create

newメソッドからデータをもらい、データベースに登録する。

castle_controller.rb
def create
  @castle.new(params[:id])
  @castle.save 
end

edit

データの編集サイトをビューに表示する。

castle_controller.rb
def edit
  @castle = Castle.find(params[:id])
end

update

編集したデータをデータベースに更新する時で使う。

castle_controller.rb
def update
    @castle = Castle.find(params[:id])
    if @castle.update(castle_params)
   (後略)

destroy

データを削除する時に使う。

castle_controller.rb
def destroy
  castle = Castle.find(params[:id])
  castle.destroy
 (後略)

参考にしたサイト

0
0
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
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?