前提・実現したいこと
Railsチュートリアルでの学習を進めていて、ダイレクトメッセージの実装に取り組んでいます。
ダイレクトメッセージの部屋(Room)を作り、JoinRoomモデルを通してUserを所属させています。
この時、userの組み合わせが全く同じRoomの作成を防ぎたいのですが、どのようにしたらいいのか見当がつきません。
例えば、idが1,2,3のuserを持つroomを複数作ることはできない、といった感じです。
ご教示の程よろしくお願いします。
コード
ruby
1 create_table "users", force: :cascade do |t| 2 t.string "name" 3 t.string "email" 4 t.datetime "created_at", null: false 5 t.datetime "updated_at", null: false 6 ~(略)~ 7 end 8 9 create_table "rooms", force: :cascade do |t| 10 t.datetime "created_at", null: false 11 t.datetime "updated_at", null: false 12 end 13 14 create_table "join_rooms", force: :cascade do |t| 15 t.integer "user_id" 16 t.integer "room_id" 17 t.datetime "created_at", null: false 18 t.datetime "updated_at", null: false 19 end 20
Ruby
1class User < ApplicationRecord 2 has_many :join_rooms, dependent: :destroy 3 has_many :rooms, through: :join_rooms, source: :room 4end
Ruby
1class Room < ApplicationRecord 2 has_many :join_rooms, dependent: :destroy 3 has_many :users, through: :join_rooms, source: :user 4end
Ruby
1class JoinRoom < ApplicationRecord 2 belongs_to :user 3 belongs_to :room 4end
補足情報(FW/ツールのバージョンなど)
Rubyのバージョン
Ruby
1$ ruby -v 2ruby 2.5.1p57
Railsのバージョン
Ruby
1$ rails -v 2Rails 5.2.3 3
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2019/08/30 02:35
2019/08/30 02:38
2019/08/30 02:46