長い時間のリスナー、初めての発信者。私は同じデータベーステーブル、チャットルームとユーザーの間に2つの関連付けを作成しようとしています。私がこれまで持っていたことは、Chatroomにメッセージを通じて多くのユーザーがいるhas_many through relationshipです。この部分はうまく動作します。私がしたいのは、Chatroom_playersというジョイン・テーブルを介して、チャットルームをユーザーに接続する2番目のジョイン・テーブルを作成することです。ですから、私が望むのは、Chatroom.first.usersがchatroom_players joinテーブルから誰かを私に連れてくるために、メッセージをテーブルとChatroom.first.playersを介して私に連れてくることです。私がこれを望むのは、ユーザーがチャットにメッセージを書き込まなくても、ユーザーがルームを離れてチャットに自分のメッセージを保持できるようにするためです。ここで 2つのジョインテーブルを同じ2つのクラスをレールアプリケーションに関連付ける方法はありますか?
は、私がこれまでに動作しないこと持っているものです。chatroom.rb:
class Chatroom < ApplicationRecord
has_many :messages, dependent: :destroy
has_many :users, through: :messages
has_many :chatroom_players
has_many :users, through: :chatroom_players
end
message.rb:
class Message < ApplicationRecord
belongs_to :chatroom
belongs_to :user
validates :content, presence: true, length: {minimum: 2, maximum: 200}
end
chatroom_player.rb
class ChatroomPlayer < ApplicationRecord
belongs_to :chatroom
belongs_to :user
end
user.rb
class User < ApplicationRecord
has_many :messages, dependent: :destroy
has_many :chatrooms, through: :messages
has_many :chatroom_players
has_many :chatrooms, through: :chatroom_players
end
chatroom_playersの移行:あなたは協会のために別の名前を使用する必要が
class AddChatroomPlayers < ActiveRecord::Migration[5.0]
def change
create_table :chatroom_players do |t|
t.references :user, index: true, foreign_key: true, null: false
t.references :chatroom, index: true, foreign_key: true, null: false
t.boolean :creator, default: false
t.timestamps null: false
end
end
end
http://guides.rubyonrails.org/association_basics.html#options-for -has-many – max
優れた答え、ありがとうございます!私があなたのスタイルでやったことは、チャットルームをゲームとしてユーザーに関連付けることでした。ユーザーはゲームやチャットルームを持ち、チャットルームはユーザーとプレイヤーを持っています。 – Jeremy
has_many:games、 through::chatroom_players、 ソース::chatroom、 class_name: "チャットルーム" – Jeremy