为什么我可以绕过 has_one 与 << 运算符的关系?

Why am I able to bypass the has_one relationship with the << operator?

示例关系如下:

class User < ActiveRecord::Base
    has_one :group, through: :group_membership
    has_one :group_membership
end

class Group < ActiveRecord::Base
  has_many :users, through: :group_memberships
  has_many :group_memberships
end

class GroupMembership < ActiveRecord::Base
    belongs_to :group
    belongs_to :user
end

为什么我可以执行以下操作?

Group.first.users << User.first
Group.second.users << User.first

我原以为 has_one 关系会阻止这种情况发生。 << 背后是否有我不知道的魔法?

User.first.group 将 return 第二组,但两组都会保留。

has_one 只能在您添加到关联的 User 端时帮助您,即。当您使用 has_one 方法本身时(没有定义 <<)。

在此处获得所需内容的最佳方法是实际更改关联,使其成为 User 端的 belongs_to。那么 User 只能与单个 Group 相关联。您可以在 group_memberships table.

中的 user_id 字段上使用唯一的数据库索引来实现类似的目的