Ruby on rails 具有关系表的用户模型

Ruby on rails 具有关系表的用户模型,ruby-on-rails,Ruby On Rails,我有两个模型用户和用户关系。这种情况是,用户自己有几个相关的用户(由他推荐),但他只有一个相关的人(推荐他的人) 我想从用户对象集合中返回推荐用户和推荐他的用户。我已经为ReturningUsers集合编写了关联,它可以工作,但我不知道应该如何编写has_one关联 我得到这个错误: ActiveRecord::HasOneThroughCantAssociateThroughCollection: Cannot have a has_one :through association 'User

我有两个模型用户和用户关系。这种情况是,用户自己有几个相关的用户(由他推荐),但他只有一个相关的人(推荐他的人)

我想从用户对象集合中返回推荐用户和推荐他的用户。我已经为ReturningUsers集合编写了关联,它可以工作,但我不知道应该如何编写
has_one
关联

我得到这个错误:

ActiveRecord::HasOneThroughCantAssociateThroughCollection: Cannot have a has_one :through association 'User#relation' where the :through association 'User#user_relations' is a collection. Specify a has_one or belongs_to association in the :through option instead
用户模型:

class User < ActiveRecord::Base
  has_many :user_relations
  has_many :related_users, through: :user_relations, source: :related_user
  has_one :relation, through: :user_relations, source: :user
end
class用户
用户关系模型:

class UserRelation < ActiveRecord::Base
  belongs_to :user
  belongs_to :related_user, class_name: 'User'
end
类用户关系
用户关系列:

  • 用户id
  • 相关用户id

我的选择是在您的用户表中为可能的相关字段添加外键

如果要求只能是一个(或没有),那么为什么不呢


您仍然为所有其他类型保留其他“用户关系”。在rails中,我们一直以不同的方式映射到同一个实体。为什么不在
UserRelation
上设置一个布尔值来指示推荐他们的用户?我假设相关的用户列是唯一的,所以不会出现两个用户推荐同一个人的情况。我不认为在那里使用布尔值有什么意义。它应该搜索相关的用户id列,并返回id等于用户id列的用户对象