ruby-on-rails - 在继承模型之上添加其他字段并公开所有父类(super class)和子类字段

标签 ruby-on-rails inheritance database-design associations single-table-inheritance

我的目标:

我正在尝试创建两种不同类型的用户,具有不同的配置文件。

Barber , Client , BarberProfile ,和ClientProfile

我有我的基地User包含类似 email 信息的对象, password ,以及 Devise 跟踪的所有其他字段。

我想要底座 User型号有一个 Profile它跟踪我希望所有用户拥有的所有基本信息。例如,first_name , last_name , avatar

我使用单表继承来创建两种不同类型的用户:ClientBarber .

我希望每种类型的用户都有一个基础 Profile与其关联,然后具有属于 BarberProfile 的其他字段和一个 ClientProfile ,分别。

BarberProfile将有 Barber 的东西需要,但是Client没有。例如,bioClientProfile将有东西Client需要,但是Barber没有。例如,hair_type .

我目前所拥有的以及我的问题:

如上所述,我为 User 创建了一个表和Profile 。所以我可以调用 user.profile.first_name 。我创建了一个BarberProfileClientProfile表以添加额外的字段。

我只想能够引用 user.profile.bio如果用户类型是Barber 。但是bio不是基本配置文件的一部分。因此,在这种情况下,我必须创建一个关联的 Profile 以及相关BarberProfile得到我需要的一切。我可以这样做 user.profile.first_nameuser.barber_profile.bio ,但感觉很困惑,而且我从本质上相同类型的模型中建立了两种不同的关联。我觉得只要有 BarberProfile 应该是一件简单的事情继承 Profile 的所有字段并添加自己的具体Barber顶部的字段。

如何在 Rails 中做到这一点?

编辑:我想要这样做的主要原因之一是我可以更新诸如 first_name 之类的内容。和bio在相同的表格中 Barber 。同样,first_namehair_type在相同的表格中 Client .

最佳答案

如果您想避免在 Profile 和 Client/BarberProfile 的用户上使用两个关联,我认为您应该使 ClientProfile 和 BarberProfile 扩展 Profile (单表继承)并且它们每个“都有一个 :barber_profile_data”(我是不知道如何调用它)。要修复长方法调用,您可以使用委托(delegate)方法。

class Barber > User
  has_one :barber_profile
  delegate :bio, to: :barber_profile

class Client < User
  has_one :client_profile
  delegate :first_name, to: :client_profile

class BarberProfile < Profile
  has_one :barber_profile_data
  delegate :bio, to: :barber_profile_data

class ClientProfile < Profile
  has_one :client_profile_data
  delegate :first_name, to: :client_profile_data

然后,当您执行“@barber.bio”时,它应该在内部调用“@barber.barber_profile.barber_profile_data.bio”。

关于ruby-on-rails - 在继承模型之上添加其他字段并公开所有父类(super class)和子类字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43433429/

相关文章:

ruby-on-rails - 有没有办法让:reserved_words option for models in FriendlyId gem does not overwrite the Rails defaults?

MySQL错误1005?

mysql - 当前具有多对多关系,但现在需要对其中一个实体进行分组

C++:如何在带有基类的父接口(interface)中实现函数?

c++ - 如何让编译器为派生类选择方法的非模板版本?

mysql - 外键可以多次使用吗?

ruby-on-rails - 使用 postgres 为 rails 提供 created_at 和 updated_at

ruby-on-rails - Ruby On Rails Mongoid 分组依据

ruby-on-rails - Rails 无法正确呈现来自 Postgres JSON 函数的嵌套 JSON 结果

python - 元类的继承