[英]Polymorphic Association ids, has_one and uniqueness
I have a polymorphic association, where an Admin and a Developer each have a User (for a common authentication mechanism) 我有一个多态关联,其中管理员和开发人员每个都有一个用户(用于通用身份验证机制)
Developer.rb 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 is identical but doesn't add any new attributes Admin.rb相同,但是不添加任何新属性
User.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
When I create Developers or Admins via the rails console, User.profile_id is always unique, and it is the same as the Developer or Admin I've just created. 当我通过Rails控制台创建Developers或Admins时,User.profile_id始终是唯一的,并且与我刚刚创建的Developer或Admin相同。 It also seems to match with the diagram here
它似乎也与这里的图相匹配
If I have a User with profile_type
= Developer
, and I want to get a reference to the Developer, is it safe to get the reference by calling Developer.find(u.profile_id)
, and similarly for Admins? 如果我有一个
profile_type
= Developer
的用户,并且想要获取对Developer的引用,是否可以通过调用Developer.find(u.profile_id)
来获取引用,对于管理员来说也一样吗? And if not, then how can I do it safely? 如果没有,那我怎么安全呢?
It works at the moment, but I'm not sure if it's just lucky because my tables are small. 目前可以使用,但是我不确定它是否很幸运,因为我的桌子很小。
Yes. 是。 The quick answer is that because you set the profile type to "Developer", the User profile id should match the one in the Developer table.
快速的答案是,因为您将配置文件类型设置为“ Developer”,所以用户配置文件ID应该与Developer表中的ID相匹配。 Imagine for a second that you have
想象一下你有
id: 1
name: Bob
profile_type: Developer
profile_id: 1
id: 2
name: Shelly
profile_type: Admin
profile_id: 1
Because you set up the polymorphic association, Rails handles all the work for you. 因为您设置了多态关联,所以Rails会为您处理所有工作。 No need to worry about id conflicts.
无需担心ID冲突。 Unless of course you change User Two to
除非您将用户2更改为
id: 2
name: Shelly
profile_type: Developer
profile_id: 1
Then Rails won't know what to do when you have two user's as the same developer. 然后,当您有两个用户作为同一开发人员时,Rails将不知道该怎么办。
And within your Developer and Admin's table you should find 在“开发者和管理员”表中,您应该找到
id: 1
skype_name Bob123
id: 1
skype_name Shelly78
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.