我有一个多态型的关联,其中,一个管理员和开发者每个有一个用户(为一个共同的认证机构)多态性关联标识,HAS_ONE和唯一
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)
参考,同样地,对于管理员?如果不是,那我该如何安全地做到这一点?
它现在有效,但我不确定它是否幸运,因为我的桌子很小。
是。快速回答是,因为你将'profile type'设置为“Developer”,User'profile id'应该匹配'Developer'表中的一个。 – jason328 2013-04-08 18:35:12
我只是困惑,那么他为什么在这个railscast中定义'find_commentable'方法:http://railscasts.com/episodes/154-polymorphic-association。 (该方法可在“注释”部分查看) – 2013-04-08 18:40:03