0
0

More than 3 years have passed since last update.

【Rails】多対多 の関連付けで、中間テーブルに複数レコードを登録する方法

Posted at

実装したい機能

多対多のモデル関係で、チェックボックスで、選択した値を複数、中間テーブルに登録させたい。
実装する際に、かなりハマってしまったので備忘録として残しておく。

環境

Rails 5.2
Ruby 2.5.1
MacOSX

モデル関係

  • プロジェクトモデル
class Project < ApplicationRecord
  has_many :project_phases, dependent: :destroy
  has_many :mst_phases, through: :project_phases
end
  • プロジェクト工程
class ProjectPhase < ApplicationRecord
  belongs_to :project
  belongs_to :mst_phase
end

  • 工程マスタ
class MstPhase < ApplicationRecord
  has_many :project_phases
end

工程に関しては、マスタテーブルで、projectモデル側を参照させないためproject_phase モデルのみを関連付けしています。

View

<%= form_with model: @project, local: true do |f| %>
  <label>プロジェクト名</label>
  <%= f.text_field :project_name %>

  <label>プロジェクト工程</label>
  <%= f.collection_check_boxes :mst_phase_ids, MstPhase.all, :id, :phase %>
<% end %>

Controller

class ProjectsController < ApplicationController

  def new
    @project = Project.new
    @project.project_phases.build
  end

  def create
    @project = Project.new(projects_params)

    if @project.save
      redirect_to project_path @project
    else
      render action: 'new'
    end
  end

  private
  def projects_params
    params.require(:project).permit( :project_name, mst_phase_ids: [])
  end
end

ポイントはStrongParameterhas_many関係にあるモデルを配列で受け取るように設定すること。

パラメータの名称は以下の要領で記載するとよい。

モデル名_ids

配列で受け取ったパラメータに対して特に特別なロジック等は実装する必要がないため、配列の要素数分、レコードをテーブルに登録してくれる。
Rails便利。。。。。

0
0
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
0