In rails 4, when using postgresql and the schema_plus gem you can just write
add_reference :posts, :author, references: :users
This will create a column author_id
, which correctly refers to users(id)
.
And in your model, you write
belongs_to :author, class_name: "User"
Note, when creating a new table you can write it as follows:
create_table :things do |t|
t.belongs_to :author, references: :users
end
Note: the schema_plus
gem in it's entirety is not compatible with rails 5+, but this functionality is offered by the gem schema_auto_foreign_keys (part of schema_plus) which is compatible with rails 5.