LoginSignup
5
3

More than 1 year has passed since last update.

【Rails】チェックボックスで複数選択した値を中間テーブルに保存する

Last updated at Posted at 2022-02-12

はじめに

中間テーブルの保存でハマった人へメモを残します。

環境

  • Ruby 2.5.9
  • Rails 5.2.6

構成

  • Furnituresテーブル { name }
  • Furniture_scenes中間テーブル { furniture_id, scene_id }
  • Scenesテーブル { name }

##手順

  • Model(アソシエーションの設定)
  • View(formの追加)
  • Controller(createアクション)
  • 完了

Model(アソシエーションの設定)

model/furniture.rb
class Furniture < ApplicationRecord
    has_many :furniture_scenes
    has_many :scenes, through: :furniture_scenes
end
model/furniture_scene.rb
class FurnitureScene < ApplicationRecord
    belongs_to :furniture
    belongs_to :scene
end
model/scene.rb
class Scene < ApplicationRecord
    has_many :furniture_scenes
    has_many :furnitures, through: :furniture_scenes
end

through: :furniture_scenesで関連するモデルを使用できるようにしています。

View(formの追加)

views/furnitures/new.html.erb
<%= form_for @furniture do |f| %>

    <%= f.label :scene_id, class: "control-label" %>
    <%= f.collection_check_boxes(:scene_ids, Scene.all, :id, :name) do |b| %>
        <label class="checkbox-inline">
        <%= b.check_box class:"form-control2" do %>
            <%= b.check_box + b.text %>
        <% end %>
            <%= b.label {b.text} %>
        </label>
    <% end %>
    <%= f.submit %>

<% end %>

collection_check_boxesの引数で指定しているScene.allでScenesテーブルから全ての項目を取得しています。
collection_check_boxesでクラスを指定できなかったので
下記の記事を参考にしました。

【Rails】Ransackのcollection_check_boxesで、checkboxタグに任意のクラスを指定する

:scene_idsは後述するcontrollerで使用します。

Controller(createアクション)

controller/furnitures_controller.rb
class FurnituresController < ApplicationController

    def create
        @furniture = Furniture.new(furniture_params)
        @furniture.save
    end

    def furniture_params
        params.require(:furniture).permit(:name, scene_ids:[])
    end
end

今回のポイントは、
Viewで使用した:scene_ids を Controllerのストロングパラメーターでscene_ids:[]とすることでした。
collection_check_boxesはどうやらXXXX_idsという配列を渡すようです。

完了

おつかれさまでした。

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