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

时间:2016-10-21 02:30:12

标签: ruby-on-rails rails-activerecord rails-migrations

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

到目前为止,这是我的工作:

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 migration:

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

1 个答案:

答案 0 :(得分: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