0

给定下表:

users
organizations
accounts
  owner_id
  owner_type
profiles

如果帐户可以由用户或组织拥有,并且每个帐户只有一个配置文件,是否可以在 Rails 中的配置文件中执行 STI 而无需“类型”字段?IE,我可以拥有根据所有权链加载的 OrganizationProfile 和 UserProfile 类,还是我需要在配置文件上有一个冗余的“类型”字段?

4

2 回答 2

0

这不是一个答案,因为它没有经过测试,但我想尝试并且我需要格式化。

对于您的代码,我认为在以下两个范围内更有意义Profile

belongs_to :account
scope :user, joins(:account).where(account: {owner_type: :User} )
scope :organization, joins(:account).where(account: {owner_type: :Organization} )

如果你想要那些你可以做的其他课程:

class UserProfile
  self.table_name = 'profiles'
  default_scope joins(:account).where(account: {owner_type: :User} )

等等与组织配置文件。

如果连接不起作用,请尝试:

joins(:account).where('accounts.owner_type = User')

或者

joins(:account).where(accounts: {owner_type: :User} )

我不确定 ActiveRecord 在那里接收哈希。

于 2013-09-05T19:59:51.350 回答
0

With STI, all records exist in the same table which inherit from the 'parent' class, in your case, Profile.

Rails uses the type field to determine what the type of a class is when deserializing, so there isn't really a way around having that on the profiles table.

于 2013-09-05T20:24:46.603 回答