Skip to content

Instantly share code, notes, and snippets.

@StanBoyet
Created November 4, 2016 09:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save StanBoyet/4d547a1cdc8ee76b56bcac471092052d to your computer and use it in GitHub Desktop.
Save StanBoyet/4d547a1cdc8ee76b56bcac471092052d to your computer and use it in GitHub Desktop.
Foreign key for named relations

In Rails 4.2+ you can also set foreign keys in the db as well, which is a great idea.

For simple associations this can be done also on t.references adding foreign_key: true, but in this case you'll need two lines.

    # The migration
    add_reference :posts, :author, references: :users, index: true
    add_foreign_key :posts, :users, column: :author_id

    # The model
    belongs_to :author, class_name: "User"
@StanBoyet
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment