【问题标题】:Rails Ownership of records in many to many relationsRails 多对多关系中记录的所有权
【发布时间】:2020-07-28 08:47:28
【问题描述】:

我正在创建一个 Rails 应用程序,但在记录所有权方面遇到了问题。

我有一个多对多的关系,我想找到记录的所有者/创建者。

型号:

class User < ApplicationRecord
 has_many :user_accounts
 has_many :accounts, through :user_accounts
end

class UserAccount < ApplicationRecord
 belongs_to :user
 belongs_to :account
end

class Account < ApplicationRecord
 has_many :user_accounts
 has_many :users, through :user_accounts
end

我怎样才能找到实际创建帐户的用户?

我曾考虑在 Account 中添加一个 owner_id 字段,并具有belongs_to 关系(例如:belongs_to :owner, class_name: 'User' ),但我想知道是否有任何其他方式或更好的方式来实现那个?

【问题讨论】:

  • 添加owner_id 对我来说似乎是一条路

标签: ruby-on-rails


【解决方案1】:

您提出的解决方案(将owner_id 添加到Account)是一个完全有效的解决方案。还有一些。

primaryowner 布尔值添加到UserAccount。由于您已经有了对帐户的引用,因此最好使用它而不是添加另一个关系。

另一个没有附加列的(!危险!,但是)是根据created_at 或类似的方法查找最早的UserAccount。不过我建议不要这样做,因为您可能进行的任何数据迁移都可能会破坏这一点。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-04
    • 2017-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-17
    相关资源
    最近更新 更多