LoginSignup
1
0

More than 3 years have passed since last update.

【超初心者的】Railsアプリ作成 Part.2 コントローラとルーティングの設定

Last updated at Posted at 2020-08-05

Part.1でデータベースのデータ登録をrails consoleで行いましたが、実際にはデータの登録はアプリの画面で行われます。ここではアプリの画面からデータベースのデータ登録や更新を行うための準備を行います。

##コントローラ作成

MVCのCです。
コントローラ名は複数形にします。ここではmenusにしています。

ターミナル
% bin/rails g controller menus index

##☆コントローラ削除

コントローラ名を間違ってしまった場合に

ターミナル
% bin/rails destroy controller menus

##ルーティング設定

〜〜〜doとendの行の間は削除して、1行追加します。これだけでいろいろなルートが設定されます。Progateと全然違うやん!!ってとまどいました。

config/routes.rb
Rails.application.routes.draw do
  resources :menus
end

##ルーティング確認

Progateの時は1行ずつパスを書いてたのに、たった1行でこれだけのルーティング設定がされました。これについては後のPartに記載します。(私は最初これを見ても意味不明だったのですが、アプリを作っていく中でなんとなくわかってきて、ちょっとうれしくなりました。)

ターミナル
% bin/rails routes
    Prefix Verb     URI Pattern                 Controller#Action
     menus GET      /menus(.:format)            menus#index
           POST     /menus(.:format)            menus#create
  new_menu GET      /menus/new(.:format)        menus#new
 edit_menu GET      /menus/:id/edit(.:format)   menus#edit
      menu GET      /menus/:id(.:format)        menus#show
           PATCH    /menus/:id(.:format)        menus#update
           PUT      /menus/:id(.:format)        menus#update
           DELETE   /menus/:id(.:format)        menus#destroy

実はこのURLにアクセスしても確認することが出来ます。
http://localhost:3000/rails/info/routes

##コントローラ設定基本形

app/controllers/menus_controller.rb
class MenusController < ApplicationController
  def index
    @menus = Menu.all
  end

  def show
    @menu = Menu.find(params[:id])
  end

  def new
    @menu = Menu.new
  end

  def edit
    @menu = Menu.find(params[:id])
  end

  def create
    @menu = Menu.new(params[:menu])
    if @menu.save
      redirect_to menus_path, notice: "作成しました"
    else
      render "new"
    end
  end

  def update
    @menu = Menu.find(params[:id])
    @menu.assign_attributes(params[:menu])
    if @menu.save
        redirect_to menus_path, notice: "更新しました"
    else
        render "edit"
    end
  end

  def destroy
    @menu = Menu.find(params[:id])
    @menu.destroy
    redirect_to menus_path, notice: "削除しました"
  end
end

defの右側に書かれているindexやnewはメソッドと呼ばれます。
Part.1で Menu.new(name: "ラーメン" 〜〜〜) というコマンドでデータを登録しましたが、このコマンドのnewがまさにそれです。newはデータを新規登録するためのメソッドなので、Menuのデータベースにデータを新規登録(new)するという意味になります。

他のメソッドはだいたい以下のような感じの意味です。アプリケーションの基本動作って感じがしますね。とりあえずこの設定があればアプリが作れます。

メソッド名 役割
index データの一覧表示
show データの詳細表示
edit データの編集
create newで登録したデータを保存する
update editしたデータを上書き保存する
destroy データを削除する

【超初心者的】Railsアプリ作成 Part.3 ビューの設定 に続く。

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