Rails 4 Migration | Add Table with Reference
This part of your migration:
t.references :collaborator, index: true, foreign_key: true
will try to create a foreign key inside the database so that the collaborator_id
column of the collaborations
table will be guaranteed to be NULL
or contain the id
of a column in the collaborators
table. You can't create that FK until the collaborators
table exists.
The error you're getting is:
relation "collaborators" does not exist
and that's just telling you that you don't have a collaborators
table but you're trying to reference it.
You need a migration to create the collaborators
table before you create your collaborations
table.
In Rails 5, at least, you can use foreign_key: {to_table: ... }} as follows.
create_table :messages, id: :uuid do |t| t.references :from_user, type: :uuid, index: true, null: false, foreign_key: {to_table: :users, on_delete: :cascade} t.references :to_user, type: :uuid, references: :user, index: true, null: false, foreign_key: {to_table: :users, on_delete: :cascade} t.text :body, null: false t.timestampsend
sorry for being late, but essentially it's all about convenience, remember that's the essence of rails. so; every reference should be targeting the table that should be in the plural (since a table holds many "objects") therefore, you must make the reference to plural so rails will generate a reference to a singular object. button line, your migration should look more like;
class CreateCollaborations < ActiveRecord::Migration def change create_table :collaborations do |t| t.references :projects, index: true, foreign_key: true t.references :collaborators, index: true, foreign_key: true t.boolean :accepted t.timestamps null: false end endend
Now, if you follow the conventions, then you should have no problem with the rest, just keep in mind that belong_to
is to a singular object and has_many
is to a plural object.
PS: I would not use past reference for the column, like accepted
Happy Coding