学生向けプログラミング入門 | 無料

学生向けにプログラミングを無料で解説。Java、C++、Ruby、PHP、データベース、Ruby on Rails, Python, Django

Rails5.1 | 11 | Webアプリケーション開発 | コントローラの編集

<<前  [TOP]  次>>


ここで、商品登録フォームはすべて日本語になり見やすくなりましたが、実際に新しい商品を登録してみると英語のメッセージが表示されたりします。
このあたりの見た目も直していきます。



コントローラファイルの編集をしていきます。
「app/controllers」フォルダにある「goods_controller.rb」ファイルを開いて下さい。
メッセージの部分のみ日本語に直しました。
【app/controllers/goods_controller.rb】

class GoodsController < ApplicationController
  before_action :set_good, only: [:show, :edit, :update, :destroy]

  # GET /goods
  # GET /goods.json
  def index
    @goods = Good.all
  end

  # GET /goods/1
  # GET /goods/1.json
  def show
  end

  # GET /goods/new
  def new
    @good = Good.new
  end

  # GET /goods/1/edit
  def edit
  end

  # POST /goods
  # POST /goods.json
  def create
    @good = Good.new(good_params)

    respond_to do |format|
      if @good.save
        format.html { redirect_to @good, notice: '商品が登録されました' }
        format.json { render :show, status: :created, location: @good }
      else
        format.html { render :new }
        format.json { render json: @good.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /goods/1
  # PATCH/PUT /goods/1.json
  def update
    respond_to do |format|
      if @good.update(good_params)
        format.html { redirect_to @good, notice: '商品の登録内容が更新されました。' }
        format.json { render :show, status: :ok, location: @good }
      else
        format.html { render :edit }
        format.json { render json: @good.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /goods/1
  # DELETE /goods/1.json
  def destroy
    @good.destroy
    respond_to do |format|
      format.html { redirect_to goods_url, notice: '商品を削除しました。' }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_good
      @good = Good.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def good_params
      params.require(:good).permit(:goods_id, :title, :description, :image_url, :price, :date, :maker, :category)
    end
end



各メソッドを解説していきます。


【respond_toメソッド】
送信されてきたリクエストを処理します。
「format.html」でHTMLを、「format.json」でJSON形式やXML形式を出力します。


【redirect_toメソッド】
指定したアクションにリダイレクトします。
「:notice」で通知用のメッセージを表示します。


【[renderメソッド】
アクションパラメータを指定することで、指定したパラメータにジャンプすることが出来ます。
「:status」パラメータはHTTPレスポンスにステータスヘッダを設定するために使います。
「:location」パラメータはHTTPレスポンスにステータスヘッダを設定するために使います。
「redirect_toメソッド」でも代用できますが、リクエストが失敗するような場合にはこの「renderメソッド」を使用した方が良いとされています。


【findメソッド】
与えられたパラメータについてSQL検索出来ます。


↓↓クリックして頂けると励みになります。


<<前  [TOP]  次>>