0

我有一个多态关联,其中管理员和开发人员各有一个用户(用于通用身份验证机制)

开发者.rb

class Developer < ActiveRecord::Base
  attr_accessible :skype_name
  has_one :user, :as => :profile, :dependent => :destroy
  accepts_nested_attributes_for :user
end

Admin.rb相同,但没有添加任何新属性

用户.rb

class User < ActiveRecord::Base
  attr_accessible :email, :name, :password, :password_confirmation, :profile_id, :profile_type
  has_secure_password

  belongs_to :profile, :polymorphic => true
  before_save { |user| user.email = email.downcase }

  ... some validations for unique email and before_save stuff ...
end

当我通过 rails 控制台创建开发人员或管理员时,User.profile_id 始终是唯一的,它与我刚刚创建的开发人员或管理员相同。它似乎也与这里的图表相匹配

如果我有一个带有profile_type=的用户Developer,并且我想获得对开发人员的引用,那么通过调用获得引用是否安全,Developer.find(u.profile_id)对于管理员也是如此?如果没有,那么我怎样才能安全地做到这一点?

它目前有效,但我不确定这是否只是幸运,因为我的桌子很小。

4

1 回答 1

1

是的。快速回答是,因为您将配置文件类型设置为“开发人员”,所以用户配置文件 ID 应该与开发人员表中的 ID 匹配。想象一下你有

用户一

id: 1
name: Bob
profile_type: Developer
profile_id: 1

用户二

id: 2
name: Shelly
profile_type: Admin
profile_id: 1

因为您设置了多态关联,Rails 会为您处理所有工作。无需担心身份冲突。当然,除非您将用户二更改为

更新用户二

id: 2
name: Shelly
profile_type: Developer
profile_id: 1

然后,当您有两个用户作为同一个开发人员时,Rails 将不知道该怎么做。

在您的开发人员和管理员表中,您应该找到

开发人员表

id: 1
skype_name Bob123

管理员表

id: 1
skype_name Shelly78
于 2013-04-08T18:41:40.020 回答