Rails - 数据的所有者 - 用户,或公司(或组)。

问题描述 投票:1回答:1

在我的应用程序的模型中,我希望有一个选项,每个记录的所有者是一个用户或一个公司... ...

通常情况下,我在每个模型中都有一个user_id字段(用户模型),用于保存所有者... ...

有什么实现方案?

我可以如何设计?

要不要在模型中再加一个字段?owner?怎么用user_id(user_model)或者company_id(company model)?

应用中的数据可以是

  • 特定用户的个人数据
  • 公司数据,与个人数据分开。当然,公司数据也是由某个用户创建的,该用户是公司的成员(具有一定的角色)......

有什么想法吗?

谅谅

ruby-on-rails authentication permissions authorization owner
1个回答
0
投票

这可以用多态关联来完成,你有一个模型可以属于1个以上具有相同关系的模型,见这个例子

class Picture < ApplicationRecord
  belongs_to :imageable, polymorphic: true
end

class Employee < ApplicationRecord
  has_many :pictures, as: :imageable
end

class Product < ApplicationRecord
  has_many :pictures, as: :imageable
end

为使其发挥作用,您需要创建一个 imageable_idimageable_type 在你的图片表上,比如这个例子。

你可以查看更多关于这个的信息 rails文档

© www.soinside.com 2019 - 2024. All rights reserved.