I am doing a coding project in rails. I have a user model, and I want to add a "spouse_id" to it (which would reference other users). Can a model reference itself in a foreign key?

  • What is the data store, for those of us not familiar with Rails? In some data stores, joins of any kind are problematic, and Rails is not the issue. – Robert Harvey Jul 24 '15 at 14:39
  • I'm not sure what you mean, but I am storing the data in a database (sqlite3 in dev; postgres in prod) – Jeff Jul 24 '15 at 14:40
  • 2
    Then the answer is "of course." It's called a self-join. – Robert Harvey Jul 24 '15 at 14:40
  • 1
    Thanks @RobertHarvey, I'm still new at this, never heard of a self-join. Now that I know what to look for: railscasts.com/episodes/163-self-referential-association – Jeff Jul 24 '15 at 14:41
  • 2
    Also called a Self-referencing table. – Robert Harvey Jul 24 '15 at 14:42

Thanks to the comments:

Then the answer is "of course." It's called a self-join.


For those who are still looking for the how-to in Rails.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.