RoomとUserという二つのモデルと、その中間テーブルとしてRoomUserがあります。
そこで、Roomを登録すると同時にRoomUserにも登録させたいと考えています。
しかし、accepts_nested_attributes_forを使って登録させたいのですが、roomsテーブルには登録されてもroom_usersテーブルには登録されませんでした。
どこが悪いのか教えていただければ嬉しいです。
よろしくお願いします。
↓コンソール上のパラメータです
Parameters: {"utf8"=>"✓", "authenticity_token"=>"02WXXlPreLySyjer0s7Pt8GveyB3pnKBzCnpbxjPofjz1WgJTGShwY8JoyjyQaBDiKbNJiePgqqsSUxIooHCPA==", "room"=>{"room_users_attributes"=>{"0"=>{"user_id"=>"1"}}, "name"=>"with friends"}, "commit"=>"新規チャットルーム作成"}
ruby
1class RoomsController < ApplicationController 2 def new 3 @room = Room.new 4 @room.room_users.build 5 end 6 7 def create 8 @room = Room.new(room_params) 9 if @room.save 10 flash[:success] = "チャットルームの登録が完了しました" 11 redirect_to @room 12 else 13 render :new 14 end 15 end 16 17 private 18 def room_params 19 params.require(:room).permit(:id, :name, room_users_attributes: [:user_id]) 20 end 21end
ruby
1class User < ApplicationRecord 2 has_many :room_users, foreign_key: 'user_id' 3 has_many :rooms, through: :room_users 4 accepts_nested_attributes_for :room_users 5 6 has_secure_password 7end
ruby
1class Room < ApplicationRecord 2 has_many :room_users, foreign_key: 'room_id' 3 has_many :users, through: :room_users 4 5 accepts_nested_attributes_for :room_users 6end
ruby
1class RoomUser < ApplicationRecord 2 belongs_to :room 3 belongs_to :user 4end
html
1<%= form_for(@room) do |f| %> 2 <%= f.fields_for :room_users do |ruf| %> 3 <%= ruf.label :name, '友人リスト' %> 4 <%= ruf.number_field :user_id %> 5 <% end %> 6 7 <%= f.label :name, 'チャットルーム名' %> 8 <%= f.text_field :name %></br> 9 10 <%= f.submit "新規チャットルーム作成" %> 11<% end %>
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2017/05/08 04:55 編集
2017/05/10 04:25