foobar
foobar

Reputation: 11374

In Rails, how to reference a model to another model through multiple columns?

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?

Upvotes: 2

Views: 168

Answers (2)

matthew.tuck
matthew.tuck

Reputation: 1317

Can you elaborate as to why you want to do this?

It's standard Rails practice that the primary key is an integer called "id", and foreign keys therefore follow this.

However, there's nothing stopping you from creating compound indexes and ensuring compound uniqueness though.

On the Post model, you can write:

validate_uniqueness_of :uid, :scope => :provider

or using the newer Rails 3 syntax:

validates :uid, :uniqueness => {:scope => :provider}

You can add compound indexes to your migrations:

add_index :posts, [:uid, :provider]

or to enforce uniqueness at the database level with unique indexes:

add_index :posts, [:uid, :provider], :unique => true

Upvotes: 0

Kai Mattern
Kai Mattern

Reputation: 3085

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/

Upvotes: 1

Related Questions