多态关联id,has_one和唯一性

时间:2013-04-08 18:30:24

标签: ruby-on-rails polymorphic-associations

我有一个多态关联,其中Admin和Developer都有一个User(用于通用的身份验证机制)

Developer.rb

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

Admin.rb 相同但不添加任何新属性

User.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始终是唯一的,它与我刚刚创建的开发人员或管理员相同。它似乎也与图here

相匹配

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

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

1 个答案:

答案 0 :(得分:1)

是。快速回答是因为您将配置文件类型设置为“Developer”,因此User配置文件ID应与Developer表中的配置文件ID匹配。想象一下你有一秒

用户一

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

用户二

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

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

更新了用户二

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

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

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

开发人员表

id: 1
skype_name Bob123

管理员表

id: 1
skype_name Shelly78