質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
Ruby

Rubyはプログラミング言語のひとつで、オープンソース、オブジェクト指向のプログラミング開発に対応しています。

Ruby on Rails 6

Ruby on Rails 6は、オープンソースのWebアプリケーションフレームワークです。「同じことを繰り返さない」というRailsの基本理念のもと、他のフレームワークより少ないコードで簡単に開発できるよう設計されています。

Q&A

解決済

1回答

1610閲覧

※追記 中間テーブルに保存されない ストロングパラメーター

kawakun-----

総合スコア13

Ruby

Rubyはプログラミング言語のひとつで、オープンソース、オブジェクト指向のプログラミング開発に対応しています。

Ruby on Rails 6

Ruby on Rails 6は、オープンソースのWebアプリケーションフレームワークです。「同じことを繰り返さない」というRailsの基本理念のもと、他のフレームワークより少ないコードで簡単に開発できるよう設計されています。

0グッド

0クリップ

投稿2021/03/23 02:33

編集2021/03/23 03:19

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

なぜ中間テーブルに保存できないのかわかりません。。。

ご教授お願いいたします。

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答1

0

ベストアンサー

ruby

1 def room_params 2 params.require(:room).permit(:name, user_id: []) 3 end

user_idではなくuser_idsではないでしょうか。

投稿2021/03/23 02:34

maisumakun

総合スコア145183

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

kawakun-----

2021/03/23 02:53 編集

ご回答ありがとうございます! フォーマットに追記させていただきましたが、 user_idsにすると上記のようなエラーになります。。。 アソシエーション等が間違っているのでしょうか。
maisumakun

2021/03/23 02:56

ロールバックが起きている場合、原因のi大半は「バリデーションに引っかかっている」です。 @room.saveに失敗したelseの側で、@room.errorsを見て何が引っかかっているか確認してみましょう。
kawakun-----

2021/03/23 03:48 編集

バリデーションを確認したところ、 genderの部分で引っかかっていました。 @userにてラジオボタンにて 記述していてその部分が上手く引き継ぎが行えていなかったことが原因でした。 再度追記しなおし、 実行すると無事保存できました。 ありがとうございました!!
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問