2016-10-21 10 views
0

長い時間のリスナー、初めての発信者。私は同じデータベーステーブル、チャットルームとユーザーの間に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 

答えて

0

class Chatroom < ApplicationRecord 
    has_many :messages, dependent: :destroy 
    has_many :users, through: :messages 
    has_many :chatroom_players 
    # this is a separate association to users through the 
    # chatroom_players table. 
    has_many :participants, 
    through: :chatroom_players, 
    source: :user, # what association on chatroom_players to use 
    class_name: 'User' # since it cannot be deduced automatically 
end 
+0

http://guides.rubyonrails.org/association_basics.html#options-for -has-many – max

+0

優れた答え、ありがとうございます!私があなたのスタイルでやったことは、チャットルームをゲームとしてユーザーに関連付けることでした。ユーザーはゲームやチャットルームを持ち、チャットルームはユーザーとプレイヤーを持っています。 – Jeremy

+0

has_many:games、 through::chatroom_players、 ソース::chatroom、 class_name: "チャットルーム" – Jeremy

関連する問題