LoginSignup
0

More than 3 years have passed since last update.

Ruby on Rails [学習記録-第13章-]

Posted at

記載内容の更新を行う

  • 編集画面を作成することができたので、続いてツイートの更新機能を実装していく。
  • ツイートを更新する際には/tweets/編集するツイートのidにpatchメソッドでアクセスする。
route.rb
Rails.application.routes.draw do
  devise_for :users
  root  'apps#index'
  get   'apps'      =>  'apps#index'
  get   'apps/new'  =>  'apps#new'
  post  'apps'      =>  'apps#create'
  delete  'apps/:id'  => 'apps#destroy'
  patch   'apps/:id'  => 'apps#update'
  get   'apps/:id/edit'  => 'apps#edit'
  get   'users/:id'  =>  'users#show'
end
  • 更新する際にはtweetsコントローラのupdateアクション。
class AppsController < ApplicationController

  before_action :move_to_index, :except => [:index]

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

  def new
  end

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

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

  def edit
    @app = App.find(params[:id])
  end

  def update
    tweet = App.find(params[:id])
    if app.user_id == current_user.id
      app.update(app_params)
    end
  end

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

  def move_to_index
    redirect_to :action => "index" unless user_signed_in?
  end
end

更新後のビューファイルを追加

update.html.erb
<div class="contents row">
  <div class="success">
    <h3>
      更新が完了しました。
    </h3>
    <a class="btn" href="/">投稿一覧へ戻る</a>
  </div>
</div>

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