gpt4 book ai didi

ruby-on-rails - 两种不同的配置文件类型

转载 作者:数据小太阳 更新时间:2023-10-29 08:01:51 25 4
gpt4 key购买 nike

假设您有两类具有不同配置文件的用户:一种是音乐艺术家,另一种是听众。每个配置文件都有一些重叠的属性和一些不同的属性。您是否应该为每个不同的配置文件创建单独的模型?或者你应该在用户表中有一个二进制数据列来判断用户是否是艺术家?这将如何构建?

最佳答案

您可以使用单表继承,这可以通过创建模型的子类来实现。

使用 type:string 列 ( The name can be overriden ) 生成一个 Profile 模型:

$ rails g model Profile type:string

现在,在 profile.rb 中,子类化您的模型:

class Profile < ActiveRecord::Base
# Common profile attributes
end

class Artist < Profile
# Things specific to an artist profile
end

class Listener < Profile
# Things specific to a listener profile
end

当您创建一个ArtistListener 时,它会与配置文件类型一起保存在profiles 表中。

例如,如果您执行 Artist.create,它将保存在 profiles 表中,type='Artist'

当您获取记录时,它将以适当的模型返回,无论是ArtistListener 还是通用的Profile

有关此技术的更多信息,请查看 this question .

This blog post也很好地解释了它。

关于ruby-on-rails - 两种不同的配置文件类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5440997/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com