有没有办法让两个连接表在 rails 应用程序中关联相同的两个 类?

Is there a way to have two join tables associate the same two classes in a rails application?

长期听众,第一次来电。我正在尝试在同一个数据库 table、聊天室和用户之间创建两个关联。到目前为止,我所拥有的是 has_many 通过关系,其中聊天室通过消息拥有许多用户。这部分工作正常。我想要做的是创建第二个连接 table,通过名为 Chatroom_players 的连接 table 将聊天室连接到用户。所以我想要的是 Chatroom.first.users 通过消息让我的用户加入 table 和 Chatroom.first.players 让我的每个人都来自 chatroom_players 加入 table。我想要这个的原因是即使用户没有在聊天中写任何消息,我也可以保持用户存在,同时用户可以离开房间但在聊天中保持他或她的消息。

这是我目前无法使用的方法:

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

您需要为关联使用不同的名称:

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