问题描述
假设一个管理员可以是一个帐户的所有者,一个帐户可以有多个管理员。您将有如下关联:
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
该代码无法正常工作,因为在 Administrator 上定义了两次的实例方法 account
相互冲突。
然后我会倾向于写这样的东西:
class Administrator < ApplicationRecord
has_one :account,as: :proprietary_account
belongs_to :account
区分关联的两个“方面”。 但是这也不起作用,并且没有创建方法property_account
有没有办法用 rails 关联建模?如果不是,您将如何在 Rails 应用中创建这种关系。
解决方法
您需要创建另一个名为 admin_accounts 的表并使用 has_many :through 关联。 admin_accounts 表将有两列,一列是 admin_id,另一列是 account_id。然后您可以通过该表关联这两个模型。更多信息请访问:https://guides.rubyonrails.org/association_basics.html#the-has-many-through-association