12
15

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 5 years have passed since last update.

複数モデル、複数レコードの一括更新(Rails)

Posted at

複数モデル、複数レコードの一括更新をしようとして少し悩んだので実装方法をメモ

##実行環境など
Rails 5.2.1
ruby 2.5.1

##テーブル構成

###teams
| id | name |
|:---------|:---------|:---------|
| 1 | チーム1 |

###members

id team_id name
1 1 一郎
2 1 次郎
3 1 三郎

##Model

team.rb
class Team < ApplicationRecord
  has_many :members
end
member.rb
class member < ApplicationRecord
  belongs_to :team

  def self.multi_update(members_params)
    members_params.to_h.map do |id, member_param|
      member = self.find(id)
      member.update_attributes!(member_param)
    end
  end
end

##Controller

team_controller.rb
class TeamsController < ApplicationController

  def edit
    @team = Team.includes(:members).find(params[:id])
  end
  def update
    team = Team.find(params[:id])
    ActiveRecord::Base.transaction do
      team.update_attributes!(team_params)
      Member.multi_update(members_params)
    end
  end

  private
    def team_params
      params.require(:team).permit(:name)
    end
    def members_params
      params.require(:team).permit(members: :name)[:members]
    end
end

##View

edit.html.slim
//ajaxを切る場合はオプションで「local: true」を指定する
= form_with model: team, url: team_path(team.id) do |f|
  label チーム名
  = f.text_field :name

  label メンバー
  - team.members.each do |member|
    = f.fields_for "members[]", member do |af|
      p 名前
      p.control
        = af.text_field :name

  = f.submit "更新"

#参考サイト
http://j-caw.co.jp/blog/?p=1590

#その他
間違いや修正点などありましたらコメントお願いします。

12
15
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
12
15

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?