LoginSignup
0
1

More than 1 year has passed since last update.

【Ruby on Rails】Formから複数のテーブルを更新する方法

Last updated at Posted at 2023-02-21

前提条件

  • Ruby 3.1.0
  • Rails 7.0.4

背景

在庫管理アプリを作成している。消費数量がFormから登録される際、同時に在庫テーブルの在庫数量を消費数量だけ減らし更新したい。

やりたいこと

消費テーブルには数量の登録、在庫テーブルには数量の更新をしたい。

テーブル情報

Stockテーブル
id
name
stock_quantity
Consumeテーブル
id
consume_quantity

方法

1.フォームから対象のStockレコードのIDを送信する

ここではcollection_selectにより更新するStockレコードのIDを送信している。

consumes/new.html.erb
<%= form_with model: [@consume] do |f| %>
  <%= f.label :名前 %></th>
  <%= f.collection_select(:stock_id, Stock.all, :id, :name, {prompt: "選択してください"} %>
  <%= f.label :消費数 %></th>
  <%= f.number_field :consume_quantity %>
<% end %>       

2.コントローラーからテーブルに追加・更新する

送信されたstock_idパラメーターから在庫テーブルの数量を更新する。
消費テーブルは普通にbuildメソッド、saveメソッドで保存する。

consume_controller
 def create
    # 消費食材を在庫テーブルから取得する
    @stock = Stock.find(params[:consume][:stock_id])

    # 在庫テーブルの数量を消費分マイナスする
    consume_quantity = params[:consume][:quantity]
    stock_quantity = @stock.stock_quantity - consume_quantity.to_i

    # 消費テーブルに登録する
    @consume = current_user.consumes.build(consume_params)

    # 保存及び更新できれば次の画面に遷移する
    if @consume.save && @stock.update_attribute(:stock_quantity, stock_quantity)
      redirect_to consumes_path
    else
      render 'new', status: :unprocessable_entity
    end
  end

  private

  def consume_params
    params.require(:consume).permit(:stock_id, :consume_quantity)
  end
0
1
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
1