在has_one关系中使用自联接模型

时间:2015-12-23 16:26:56

标签: ruby-on-rails ruby-on-rails-4

我的captain模型上有一个自我加入模型user。我在与一个team模型的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

我遇到了使用@team.captain的问题,因为captain_id位于用户数据库表中,但它检索的第一个用户team_id等于@team.id. Using has_one:队长,:through =&gt; :user`给出关联错误。任何建议表示赞赏。感谢。

1 个答案:

答案 0 :(得分:2)

尝试为关联指定foreign_key

has_one  :captain, :class_name => "User", :foreign_key => 'captain_id'
相关问题