2 次引用同一模型,但没有 has_and_belongs_to_many

2 references to same model without has_and_belongs_to_many

class Message < ActiveRecord::Base
  belongs_to :conversation
  belongs_to :user
end

class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  has_many :conversations
  has_many :conversations, class_name: "Conversation", foreign_key: :user2_id
end


class Conversation < ActiveRecord::Base
    belongs_to :user
    belongs_to :user2, class_name: "User", foreign_key: :user2_id
    has_many :messages
end

spec:

require 'rails_helper'

RSpec.describe Message, type: :model do
    it "should be available to 2 users" do
        u = User.create(email: 'x@y.com', password: '8888888888')
        u2 = User.create(email: 'z@w.com', password: '8888888888')
        c = Conversation.create(user_id: u.id, user2_id: u2.id)
        expect(u2.conversations.count).to eq 1
        expect(u.conversations.count).to eq 1
    end
end

是这一行:

expect(u.conversations.count).to eq 1

失败了。

大概是因为我的第二个has_many

但是如果我删除它,那么 expect(u2.conversations.count).to eq 1 会失败。

是的,我明确希望对话中只有 2 个用户。我试图避免做 HABTM。

我该如何进行这项工作?

has_many :conversations
has_many :conversations, class_name: "Conversation", foreign_key: :user2_id

你只能有 1 个 has_many 的集合名称。随着 ruby class 加载,您的第一个 has_many 正在被第二个覆盖。我想不出更好的名字,但你应该给其中一个取不同的名字,也许可以用来证明发起对话的人。

您可以将 has_many :through 与连接模型一起使用。以下是如何设置的说明:http://www.tweetegy.com/2011/02/setting-join-table-attribute-has_many-through-association-in-rails-activerecord/.