开发者

Three way omniauth authentications relationship. How to set it up?

开发者 https://www.devze.com 2023-02-15 14:39 出处:网络
I\'ve implemented facebook and twitter authentication in an app I\'m working on by following the excellent Railscasts videos on the topic.

I've implemented facebook and twitter authentication in an app I'm working on by following the excellent Railscasts videos on the topic.

Thus far I have my user model hooked up with Devise and I have my Authentications model built and recording authentication providers when users sign up via them. It looks like this:

id | user_id | provider | uid
-----------------------------
1  |    1    | facebook | xyf
2  |    1    | twitter  | pfr
3  |    2    | faceb开发者_StackOverflowook | sdf

Now, the next thing I need is to store some of the data that these omniauth providers give me. Facebook for example provides the users gender and the url for their facebook profile. A connection to twitter on the other hand will provide different information on a user.

This leads me to believe that I should have two tables, one for twitter data (TwitterProfile) and one for facebook data (FacebookProfile).

So should I extend my authentications model like this?

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            | 

and the my models/user.rb would look something like:

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

But can my authentications model belong to 3 tables?

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

It just seems like I'm on the wrong track because I have redundant space in my authentications model ant the relationships seem overly complicated.


You might want to consider a polymorphic association. Say the association is called Profile. Basically, the association has a single profile_id, and a string profile_type column, which indicates what type of profile each authentication has.

There are lots of resources explaining how to set this up including a Railscast video, a section in the Rails Guides and it's in the Rails API too.

0

精彩评论

暂无评论...
验证码 换一张
取 消