Let’s say we’re making a blog. Usually, the models look like this:
class User
has_many :posts
end
class Post
belongs_to :user
end
And their schemas look like:
User
id
Post
id
user_id
But now, users can log in through Facebook/Twitter/etc, and we want a post to belong not to the User object, but rather to the combination of the provider and the uid of provider.
The new schema would look like:
User
id
provider
uid
Post
id
user_provider
user_uid
And I’m not sure how the models would look like:
class User
has_many :posts, :foreign_key => ['user_provider', 'user_uid'] # Is this right??
end
class Post
belongs_to :user, :class_name => User # Again, this is a guess...
end
Am I on the right track? What is the Rails way of doing this?
You cannot have composite primary keys in rails out of the box. Fot that I think you will have to use gems. I would advise you to find a workaround.
However to have a starting point, look here:
http://compositekeys.rubyforge.org/