###前提・実現したいこと
ruby on railsであるグループを作る際に、そのグループにuserも登録して、そのグループにどのユーザーが属しているかをaccepts_nested_attributes_forを使って中間テーブルに登録したいです。
具体的にはビューにチェックボックスを作ってそこからグループに登録したいユーザーを選びます
チェックボックスは
f.collection_check_boxes :user_ids, User.all, :id, :name
を用いて作りました。
例えばすべてのユーザーにチェックを入れてSENDするとユーザのidが7,8,9としてparamasが
params.require(:group).permit(:name, user_ids:[]) => {"name"=>"テストグループ", "user_ids"=>["","7", "8", "9"]}
という風に取得することはできました。
user_idsの配列に""と空になっているものが送られてきてるのはcollection_check_boxesの仕様のようです 参考記事
このテストグループという名前のグループ(id 10として)をgroupテーブルに保存しつつ、
accepts_nested_attributes_forを用いてusers_groupsテーブルに
groups table
id | name |
---|---|
10 | テストグループ |
users_groups table
id | group_id | user_id |
---|---|---|
1 | 10 | 7 |
2 | 10 | 8 |
3 | 10 | 9 |
と保存したいのですが、コントローラーにどのように書けばいいのかがわかりません。
教えていただけないでしょうか?
###テーブルとモデル
users table
column | type |
---|---|
name | string |
string | |
password | string |
class User < ApplicationRecord devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable #association has_many :users_groups has_many :groups, through: :users_groups end
groups table
column | type |
---|---|
name | string |
class Group < ApplicationRecord #association has_many :users_groups has_many :users, through: :users_groups accepts_nested_attributes_for :users_groups end
users_groups table
|column|type|
|:--|:--|:--|
|user_id|references|
|group_id|references|
class UsersGroup < ApplicationRecord #association belongs_to :user belongs_to :group end
###補足情報(言語/FW/ツール等のバージョンなど)
より詳細な情報
rails 5.0.0
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2017/04/06 15:00
2017/04/06 23:41
2017/04/08 07:32