Ruby on rails 在has_-one关系中使用自连接模型

Ruby on rails 在has_-one关系中使用自连接模型,ruby-on-rails,ruby-on-rails-4,Ruby On Rails,Ruby On Rails 4,我在我的用户模型上有一个自加入模型船长。我在使用队长与团队模型的has_-one关系时遇到问题,该模型已经与用户模型存在has_-many关系 我的团队模式 class Team < ActiveRecord::Base validates :teamname, :teamcolor, presence: true has_one :captain, :class_name => "User" #, :through => :user has_many

我在我的
用户
模型上有一个自加入模型
船长
。我在使用队长与
团队
模型的has_-one关系时遇到问题,该模型已经与用户模型存在has_-many关系

我的团队模式

class Team < ActiveRecord::Base

  validates :teamname, :teamcolor, presence: true

  has_one  :captain, :class_name => "User"
   #, :through => :user
  has_many :users


  #after_save :set_default_captain

  accepts_nested_attributes_for :users
  accepts_nested_attributes_for :captain
end
class User < ActiveRecord::Base

  attr_accessor :remember_token

  before_save {self.email = email.downcase }
  VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z\d\-]+)*\.[a-z]+\z/i
  validates :email, presence: true, length: { maximum: 255 },
                         format:{with: VALID_EMAIL_REGEX}, 
                         uniqueness: { case_sensitive: false }

  has_secure_password
  validates :password, presence: true, length: { minimum: 6 }, allow_nil: true

  has_one :profile, inverse_of: :user, dependent: :destroy
  has_many :teammates, :class_name => "User", :foreign_key => "captain_id"

  belongs_to :captain, :class => "User"
  belongs_to :team


  accepts_nested_attributes_for :team
end
class团队“用户”
#,:至=>:用户
有很多:用户
#保存后:设置默认值
接受用户的\u嵌套\u属性\u
接受:船长的\u嵌套\u属性\u
结束
我的用户模型

class Team < ActiveRecord::Base

  validates :teamname, :teamcolor, presence: true

  has_one  :captain, :class_name => "User"
   #, :through => :user
  has_many :users


  #after_save :set_default_captain

  accepts_nested_attributes_for :users
  accepts_nested_attributes_for :captain
end
class User < ActiveRecord::Base

  attr_accessor :remember_token

  before_save {self.email = email.downcase }
  VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z\d\-]+)*\.[a-z]+\z/i
  validates :email, presence: true, length: { maximum: 255 },
                         format:{with: VALID_EMAIL_REGEX}, 
                         uniqueness: { case_sensitive: false }

  has_secure_password
  validates :password, presence: true, length: { minimum: 6 }, allow_nil: true

  has_one :profile, inverse_of: :user, dependent: :destroy
  has_many :teammates, :class_name => "User", :foreign_key => "captain_id"

  belongs_to :captain, :class => "User"
  belongs_to :team


  accepts_nested_attributes_for :team
end
class用户“User”,:foreign\u key=>“captain\u id”
属于:船长,:class=>“用户”
属于:团队
接受:团队的\u嵌套\u属性\u
结束

我在使用
@team.captain
时遇到问题,因为
captain\u id
在用户数据库表中,但它正在检索具有
team\u id
等于
@team.id的第一个用户。使用
有一个:captain,:through=>:user`给出关联错误。任何建议都将不胜感激。谢谢。

尝试为关联指定
外键

has_one  :captain, :class_name => "User", :foreign_key => 'captain_id'

对于自联接,
是否优先于
所属的