ruby-on-rails - 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 应用程序中创建这种关系。
解决方案
您需要创建另一个名为 admin_accounts 的表并使用 has_many :through 关联。admin_accounts 表将有两列,一列带有 admin_id,一列带有 account_id。然后,您可以通过该表关联这两个模型。更多信息在这里:https ://guides.rubyonrails.org/association_basics.html#the-has-many-through-association
推荐阅读
- typescript - 比特币价值的 ECDSA:什么是 z?
- firebase - 在没有模拟器的情况下在本地测试 firebase 云功能
- typescript - 类型 '() => Bar' 缺少来自类型 'Bar' 的以下属性:x、y
- excel - 如何加快在 Excel VBA 中触发 shell 命令?
- javascript - Google 应用脚本 getvalue 和 setvalue 到另一张表需要 3 分钟,并希望简化
- php - nginx:为什么我在尝试访问 wordpress 时访问被拒绝?
- flutter - 使用 DartZ 调用多个 Future 时如何避免嵌套折叠?
- python - 在python中的列表中添加条件
- javascript - Chart.js 颜色没有动态更新
- c# - 实体框架核心一对一,不唯一