4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【Rails】1つのコントローラに2つ目のupdateの役割をするアクションを作る

Last updated at Posted at 2023-06-22

Webアプリ作成中

・押すボタンによって、それぞれ別のカラムを変更し、上書きするアクションをつけた際の流れ
routes.rb
resources :study_times, only: %i[new create index update] do
    member do
      patch :finish
    end
  end

・resources :study_timesに対してmemberメソッドを使用し、finishアクションを定義。
・これにより、個別のstudy_timeオブジェクトに対してfinishアクションを実行できる。
・patchメソッドを使用しているため、HTTPのPATCHリクエストがfinishアクションに対して送信される。

study_times_controller.rb
class StudyTimesController < ApplicationController
  def update
    @study_time = StudyTime.find(params[:id])
    elapsed_time = (Time.now - @study_time.created_at) / 60
    @study_time.total_time = elapsed_time.to_i
    @study_time.touch(:updated_at)
    @study_time.save
    redirect_to study_times_path
  end

  def finish
    @study_time = StudyTime.find(params[:id])
    @study_time.status = 1
    @study_time.save
    redirect_to study_times_path
  end

・updateアクション、finishアクションは共に、study_timeインスタンスのカラムを変更し、上書きするアクション

_study_time.html.erb
<%= form_with(model: study_time, url: study_time_path(study_time)) do |f| %>
    <%= f.submit "更新", class: "btn btn-primary" %>
<% end %>
<%= form_with(model: study_time, url: finish_study_time_path(study_time)) do |f| %>
    <%= f.submit "終了", class: "btn btn-secondary" %>
<% end %>

・ちなみにviewはこのような形で、リクエストを飛ばす

4
3
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
4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?