前提・実現したいこと
チャットアプリを作ろうとしているのですがroomとuserは多対多なのでroom_usersの中間テーブルを作ってアソシエーションを通さなければなりません。しかしコードをちゃんと書いているはずなのですがseaquel proでデータベースを見てみるとroom_usersの方ではデータが保存されません。roomとuserのデータは保存されています。中間テーブルにも保存出来る様にしたい。(エラーメッセージは出ていません。)
先日railsバージョン5.1以上の場合はreferenes型がbigint型になるのでとご回答いただいてmigrateの:roomと:userにtypeを追加してそれを回避したのですがそれでもデータを保存できません。
該当のソースコード
ruby
1migrateファイル 2class CreateRoomUsers < ActiveRecord::Migration[6.0] 3 def change 4 create_table :room_users do |t| 5 t.references :room, type: :bigint,foreign_key: true 6 t.references :user, type: :bigint,foreign_key: true 7 t.timestamps 8 end 9 end 10end
ruby
1models/room.rb 2 3class Room < ApplicationRecord 4 has_many :room_users 5 has_many :users, through: :room_users 6 has_many :messages 7 8 validates :name, presence: true 9end 10
ruby
1models/user.rb 2 3class User < ApplicationRecord 4 devise :database_authenticatable, :registerable, 5 :recoverable, :rememberable, :validatable 6 with_options presence: true do 7 validates :nickname 8 validates :team_id 9 end 10 validates :team_id, numericality: {other_than: 1} 11 def remember_me 12 true 13 end 14 has_many :room_users 15 has_many :rooms, through: :room_users 16 has_many :messages 17end 18
ruby
1models/room_user.eb 2 3class RoomUser < ApplicationRecord 4 belongs_to :room 5 belongs_to :user 6end 7
html
1index.html.erb ←追記 2 3 <%=form_with model: @room, local: true do |f|%> 4 <%= f.label :チャットルーム名, class: 'chat-room-form__label'%> 5 <div class='chat-room-form__field--right'> 6 <%= f.text_field :name, class: 'chat__room_name chat-room-form__input', placeholder: 'チャットルーム名を入力してください'%> 7 </div> 8 <%= f.label :内容, class: 'chat-room-form__label'%> 9 <div class='chat-room-form__field--right'> 10 <%= f.text_area :content, class: 'chat__room_name chat-room-form__input', size: "30×30"%> 11 </div> 12 <%= f.submit class: 'chat-room-form__action-btn'%> 13 <%end%>
ruby
1rooms_controller←追記 2 3class RoomsController < ApplicationController 4 def index 5 @room = Room.new 6 @rooms = Room.all.order(id: "DESC") 7 end 8 def create 9 @room = Room.new(room_params) 10 if @room.save 11 redirect_to root_path 12 else 13 render :inde 14 end 15 end 16 def destroy 17 room = Room.find(params[:id]) 18 room.destroy 19 redirect_to root_path 20 end 21 22 private 23 def room_params 24 params.require(:room).permit(:name,:content, user_ids:[]) 25 end 26end
ログ←追記 Started POST "/rooms" for ::1 at 2020-08-29 17:15:37 +0900 Processing by RoomsController#create as HTML Parameters: {"authenticity_token"=>"MDb1owe+4mdaAauyjwGJquTMrrtKUd1fbinr0e3nbBxD65/ZhUaDJjkSYNV4eMDIWFs3YNqrf1UzKCRqboJZVg==", "room"=>{"name"=>"テストチャットルーム", "content"=>"test"}, "commit"=>"Create Room"} (0.1ms) BEGIN ↳ app/controllers/rooms_controller.rb:8:in `create' Room Create (0.3ms) INSERT INTO `rooms` (`name`, `content`, `created_at`, `updated_at`) VALUES ('テストチャットルーム', 'test', '2020-08-29 08:15:37.661242', '2020-08-29 08:15:37.661242') ↳ app/controllers/rooms_controller.rb:8:in `create' (0.3ms) COMMIT ↳ app/controllers/rooms_controller.rb:8:in `create' Redirected to http://localhost:3000/ Completed 302 Found in 5ms (ActiveRecord: 0.8ms | Allocations: 3370) Started GET "/" for ::1 at 2020-08-29 17:15:37 +0900 Processing by RoomsController#index as HTML Rendering rooms/index.html.erb within layouts/application Rendered shared/_header.html.erb (Duration: 0.0ms | Allocations: 6) User Load (0.3ms) SELECT `users`.* FROM `users` WHERE `users`.`id` = 1 ORDER BY `users`.`id` ASC LIMIT 1 ↳ app/views/rooms/index.html.erb:9 Room Load (0.3ms) SELECT `rooms`.* FROM `rooms` ORDER BY `rooms`.`id` DESC ↳ app/views/rooms/index.html.erb:101 Rendered rooms/index.html.erb within layouts/application (Duration: 28.1ms | Allocations: 14430) [Webpacker] Everything's up-to-date. Nothing to do Completed 200 OK in 40ms (Views: 38.6ms | ActiveRecord: 0.6ms | Allocations: 26544)
ログ←rails c 追記 from /Users/hatea/.rbenv/versions/2.6.5/lib/ruby/gems/2.6.0/gems/mysql2-0.5.3/lib/mysql2/client.rb:131:in `_query' [4] pry(main)> User.create(nickname: "hoge", email: "example@fuga.com", password: "123456", password_confirmation: "123456",team_id: "2",favorite_player: "",introduction: "") (0.2ms) BEGIN User Exists? (0.3ms) SELECT 1 AS one FROM `users` WHERE `users`.`email` = BINARY 'example@fuga.com' LIMIT 1 User Create (0.2ms) INSERT INTO `users` (`nickname`, `team_id`, `favorite_player`, `introduction`, `email`, `encrypted_password`, `created_at`, `updated_at`) VALUES ('hoge', 2, '', '', 'example@fuga.com', '$2a$12$dWYbTILaK0K6lKLiwYRIme9Ugc83KZqeR/2ko.vipKc2Eco7YQbi6', '2020-08-30 02:35:32.726778', '2020-08-30 02:35:32.726778') (0.9ms) COMMIT => #<User id: 2, nickname: "hoge", team_id: 2, favorite_player: "", introduction: "", email: "example@fuga.com", created_at: "2020-08-30 02:35:32", updated_at: "2020-08-30 02:35:32"> [8] pry(main)> Room.create(name: "ルーム1", user_ids:1, content:"") User Load (0.5ms) SELECT `users`.* FROM `users` WHERE `users`.`id` = 1 (0.2ms) BEGIN Room Create (0.2ms) INSERT INTO `rooms` (`name`, `content`, `created_at`, `updated_at`) VALUES ('ルーム1', '', '2020-08-30 02:38:29.885077', '2020-08-30 02:38:29.885077') RoomUser Create (0.2ms) INSERT INTO `room_users` (`room_id`, `user_id`, `created_at`, `updated_at`) VALUES (9, 1, '2020-08-30 02:38:29.886483', '2020-08-30 02:38:29.886483') (0.5ms) COMMIT => #<Room:0x00007ff5eb34a650 id: 9, name: "ルーム1", content: "", created_at: Sun, 30 Aug 2020 11:38:29 JST +09:00, updated_at: Sun, 30 Aug 2020 11:38:29 JST +09:00>
試したこと
最新の状態で再起動
補足情報(FW/ツールのバージョンなど)
rails 6.0.0 ,gem "devise"
回答2件
あなたの回答
tips
プレビュー