首页 > 解决方案 > Rails:has_one 和 belongs_to 相同的模型

问题描述

假设一个管理员可以是一个帐户的所有者,一个帐户可以有多个管理员。您将有如下关联:

class Account < ApplicationRecord
   belongs_to :account_owner, foreign_key: :account_owner_id, class_name: 'Administrator', optional: true
   has_many :administrators
end

class Administrator < ApplicationRecord
 # account instance has an account_owner_id that references the administrator "app owner"
 has_one :account
 # administrator has an account_id on it that references the account he belongs_to
 belongs_to :account

该代码无法正常工作,因为account在管理员上定义的两次实例方法相互冲突。

然后我会倾向于写这样的东西:

class Administrator < ApplicationRecord
  has_one :account, as: :proprietary_account
  belongs_to :account

区分关联的两个“方面”。但是,这也不起作用,并且没有创建方法proprietary_account

有没有办法用 rails 关联建模?如果不是,您将如何在 Rails 应用程序中创建这种关系。

标签: ruby-on-railsassociationsbelongs-tohas-one

解决方案


您需要创建另一个名为 admin_accounts 的表并使用 has_many :through 关联。admin_accounts 表将有两列,一列带有 admin_id,一列带有 account_id。然后,您可以通过该表关联这两个模型。更多信息在这里:https ://guides.rubyonrails.org/association_basics.html#the-has-many-through-association


推荐阅读