Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 4 Migration | Add Table with Reference

I am attempting to create a Collaboration table in my Rails 4 project, but I've run into an issue. I wish it to belong_to a single user, the collaborator.

I ran the following command to generate the model and the migration, which I've also copied below.

rails generate model Collaboration project:references collaborator:references accepted:boolean

Migration:

class CreateCollaborations < ActiveRecord::Migration
    def change
        create_table :collaborations do |t|
            t.references :project, index: true, foreign_key: true
            t.references :collaborator, index: true, foreign_key: true
            t.boolean :accepted

            t.timestamps null: false
        end
    end
end

Model:

class Collaboration < ActiveRecord::Base
    belongs_to :project
    belongs_to :collaborator, class_name: 'User'
end

I updated the Collaboration model to include , class_name: 'User' as shown above. Similarly, I updated the existing Strategy model to include a has_many :collaborations

class Project < ActiveRecord::Base
    has_many :collaborations
end

When I run rake db:migrate, I get the following error reported.

rake aborted!
StandardError: An error has occurred, this and all later migrations canceled:

PG::UndefinedTable: ERROR:  relation "collaborators" does not exist

I'm a bit puzzled as to wy this is happening. Any assistance would be greatly appreciated! Thank you. :)

EDIT:

Adding code for my User model as well.

class User < ActiveRecord::Base
    authenticates_with_sorcery!

    has_many :projects
    has_many :collaborations
end

I edited out validations for fields such as password, email, etc to try to remove clutter.

like image 268
Michael Fich Avatar asked Aug 15 '15 04:08

Michael Fich


1 Answers

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.timestamps
end
like image 65
Samuel Danielson Avatar answered Oct 07 '22 00:10

Samuel Danielson