roomテーブルには保存されたが
room_usersテーブルには保存されません。
rails6.0.0にて
メッセージ機能を実装中です。
現在下記のようにroomを作成しており、
userテーブル,roomテーブル,room_usersテーブルと中間テーブルを作成しています。
roomコントローラー
class RoomsController < ApplicationController def new @room = Room.new end def create @room = Room.new(room_params) if @room.save redirect_to room_messages_path(@room) else render :new end end private def room_params params.require(:room).permit(:name, user_id: []) end end
userモデル
※省略 has_many :room_users has_many :rooms, through: :room_users has_many :messages
roomモデル
has_many :room_users has_many :users, through: :room_users has_many :messages validates :name,presence: true
room_usersモデル
belongs_to :room belongs_to :user
roomビュー
<div class='chat-room-form'> <h1>Message</h1> <%=form_with model: @room, local: true do |f|%> <div class='chat-room-form__field'> <div class='chat-room-form__field--left'> <%= f.label :Neme, class: 'chat-room-form__label'%> </div> <div class='chat-room-form__field--right'> <%= f.text_field :name, class: 'chat__room_name chat-room-form__input', placeholder: 'Nameを入力してください'%> </div> </div> <div class='chat-room-form__field'> </div> <div class='chat-room-form__field'> <div class='chat-room-form__field--left'> <label class='chat-room-form__label' for='chat_room_チャットメンバー'>Menber</label> </div> <div class='chat-room-form__field--right'> <select name="room[user_ids][]"> <option value="">ユーザーを選択してください</option> <% User.where.not(id: current_user.id).each do |user| %> <option value=<%= user.id %>><%= user.name %></option> <% end %> </select> <input name="room[user_ids][]" type="hidden" value=<%= current_user.id %>> </div> </div> <div class='chat-room-form__field'> <div class='chat-room-form__field--left'></div> <div class='chat-room-form__field--right'> <%= f.submit class: 'chat-room-form__action-btn'%> </div> </div> <% end %> </div>
エラーメッセージ User Load (0.5ms) SELECT `users`.* FROM `users` WHERE `users`.`id` = 6 ORDER BY `users`.`id` ASC LIMIT 1 Unpermitted parameter: :user_ids (0.1ms) BEGIN
該当のソースコード
def room_params params.require(:room).permit(:name, user_id: []) end
ストロングパラーメーターが
roomではuser_idsがカラムがなく呼び出せないとのことだったので、
user_idに変更しましたが中間テーブルには保存されませんでした。。。
試したこと
paramsでpryをかけてみると、
[1] pry(#<RoomsController>)> params => <ActionController::Parameters {"authenticity_token"=>"eh1NOUMrkCr3XudxU19Thx7fuw6wnL5/oITluHFjjc7gDQKqnSsDSU4TOGgLxi2f/fMCXQBUbKZMAbQdwTbAag==", "room"=>{"name"=>"kawa", "user_ids"=>["2", "6"]}, "commit"=>"Create Room", "controller"=>"rooms", "action"=>"create"} permitted: false>
コントローラーにuser_idsで記載してみると、
ターミナルに下記のようなエラーが出ます。。。
(0.4ms) SET NAMES utf8, @@SESSION.sql_mode = CONCAT(CONCAT(@@sql_mode, ',STRICT_ALL_TABLES'), ',NO_AUTO_VALUE_ON_ZERO'), @@SESSION.sql_auto_is_null = 0, @@SESSION.wait_timeout = 2147483 Processing by RoomsController#create as HTML Parameters: {"authenticity_token"=>"al727tBbTypIjy3vZRnlciMGVnQ3lfvesTH94yYqIH3wTrl9DlvcSfHC8vY9gJtqwCrvJ4ddKQddtKxGln9t2Q==", "room"=>{"name"=>"aa", "user_ids"=>["2", "6"]}, "commit"=>"Create Room"} User Load (0.8ms) SELECT `users`.* FROM `users` WHERE `users`.`id` = 6 ORDER BY `users`.`id` ASC LIMIT 1 User Load (0.6ms) SELECT `users`.* FROM `users` WHERE `users`.`id` IN (2, 6) ↳ app/controllers/rooms_controller.rb:8:in `create' (0.2ms) BEGIN ↳ app/controllers/rooms_controller.rb:9:in `create' ActiveStorage::Attachment Load (1.2ms) SELECT `active_storage_attachments`.* FROM `active_storage_attachments` WHERE `active_storage_attachments`.`record_id` = 2 AND `active_storage_attachments`.`record_type` = 'User' AND `active_storage_attachments`.`name` = 'image' LIMIT 1 ↳ app/controllers/rooms_controller.rb:9:in `create' ActiveStorage::Attachment Load (0.6ms) SELECT `active_storage_attachments`.* FROM `active_storage_attachments` WHERE `active_storage_attachments`.`record_id` = 6 AND `active_storage_attachments`.`record_type` = 'User' AND `active_storage_attachments`.`name` = 'image' LIMIT 1 ↳ app/controllers/rooms_controller.rb:9:in `create' (0.1ms) ROLLBACK ↳ app/controllers/rooms_controller.rb:9:in `create' Rendering rooms/new.html.erb within layouts/application User Load (0.4ms) SELECT `users`.* FROM `users` WHERE `users`.`id` != 6 ↳ app/views/rooms/new.html.erb:21 Rendered rooms/new.html.erb within layouts/application (Duration: 1.9ms | Allocations: 1406) [Webpacker] Everything's up-to-date. Nothing to do Completed 200 OK in 86ms (Views: 14.0ms | ActiveRecord: 10.9ms | Allocations: 53947)
@room.errors確認してみると
7: def create 8: @room = Room.new(room_params) 9: if @room.save 10: redirect_to room_messages_path(@room) 11: else 12: render :new => 13: binding.pry 14: end 15: end [1] pry(#<RoomsController>)> @room.errors => #<ActiveModel::Errors:0x00007fceba1fc148 @base=#<Room:0x00007fceb9f546e8 id: nil, name: "aa", created_at: nil, updated_at: nil>, @details={:users=>[{:error=>:invalid}, {:error=>:invalid}]}, @messages={:users=>["is invalid"], :Neme=>[], :name=>[]}>
バリデーションが原因の可能性が高いということで
userモデル
class User < ApplicationRecord devise :database_authenticatable, :registerable, :recoverable, :rememberable, :validatable with_options presence: true do validates :name validates :birth_day validates :gender validates :hobby validates :self_introduction, length: { maximum: 200 } validates :image end enum gender: { man: 0, woman: 1} has_one_attached :image has_many :relationships has_many :followings, through: :relationships, source: :follow has_many :reverse_of_relationships, class_name: 'Relationship', foreign_key: 'follow_id' has_many :followers, through: :reverse_of_relationships, source: :user def follow(other_user) unless self == other_user self.relationships.find_or_create_by(follow_id: other_user.id) end end def unfollow(other_user) relationship = self.relationships.find_by(follow_id: other_user.id) relationship.destroy if relationship end def following?(other_user) self.followings.include?(other_user) end has_many :room_users has_many :rooms, through: :room_users has_many :messages end
なぜ中間テーブルに保存できないのかわかりません。。。
ご教授お願いいたします。
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2021/03/23 02:53 編集
2021/03/23 02:56
2021/03/23 03:48 編集