在我的应用程序的模型中,我希望有一个选项,每个记录的所有者是一个用户或一个公司... ...
通常情况下,我在每个模型中都有一个user_id字段(用户模型),用于保存所有者... ...
有什么实现方案?
我可以如何设计?
要不要在模型中再加一个字段?owner?怎么用user_id(user_model)或者company_id(company model)?
应用中的数据可以是
有什么想法吗?
谅谅
这可以用多态关联来完成,你有一个模型可以属于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_id
和 imageable_type
在你的图片表上,比如这个例子。
你可以查看更多关于这个的信息 rails文档