三路omniauth认证关系。如何设置?

时间:2011-03-07 21:20:33

标签: ruby-on-rails ruby-on-rails-3 database-design omniauth

我已经在我正在处理的应用中实施了facebook和twitter身份验证,并遵循了该主题的优秀Railscasts videos

到目前为止,我的用户模型已与Devise连接,我建立了Authentications模型,并在用户通过它们注册时记录身份验证提供程序。它看起来像这样:

id | user_id | provider | uid
-----------------------------
1  |    1    | facebook | xyf
2  |    1    | twitter  | pfr
3  |    2    | facebook | sdf

现在,我需要的下一件事是存储这些omniauth提供商给我的一些数据。例如,Facebook提供用户性别和他们的Facebook个人资料的网址。另一方面,与Twitter的连接将提供有关用户的不同信息。

这让我相信我应该有两个表,一个用于Twitter数据(TwitterProfile),另一个用于Facebook数据(FacebookProfile)。

我应该像这样扩展我的身份验证模型吗?

id | user_id | provider | uid | facebook_profile_id | twitter_profile_id
------------------------------------------------------------------------
1  |    1    | facebook | xyf |        1            |          
2  |    1    | twitter  | pfr |                     |         2
3  |    2    | facebook | sdf |        2            | 

我的models / user.rb看起来像是:

has_many :authentications, :dependent => :destroy
has_one :facebook_profile, :through => :authentications, :source => :facebook_profile
has_one :twitter_profile, :through => :authentications, :source => :twitter_profile

但我的身份验证模型可以属于3个表吗?

  belongs_to :user
  belongs_to :facebook_profile, :class_name => "FacebookProfile"
  belongs_to :twitter_profile, :class_name => "TwitterProfile"

似乎我走错了路,因为我的身份验证模型中有冗余空间,这种关系似乎过于复杂。

1 个答案:

答案 0 :(得分:1)

您可能想要考虑多态关联。假设该关联称为Profile。基本上,关联具有单个profile_id和字符串profile_type列,该列指示每个身份验证具有的配置文件类型。

有很多资源解释了如何设置此问题,包括Railscast videoRails Guides中的一个部分以及Rails API中的部分。