Question

I am trying to create a user_roles table in my engine that joins the user with a particular role allowing that user to have one or more roles.

I have the following migrations:

User

-- This migration works fine.

class CreateXaaronUsers < ActiveRecord::Migration
  def change
    create_table :xaaron_users do |t|
      t.string :first_name
      t.string :last_name
      t.string :user_name
      t.string :email
      t.string :password
      t.string :salt

      t.timestamps
    end
  end
end

Roles

-- This migration works fine

class Roles < ActiveRecord::Migration
  def change
    create_table :xaaron_roles do |t|
      t.string :role
      t.timestamps
    end
  end
end

user_roles

-- This migration explodes stating that column user_id doesn't exist. I assume that this migration, dealing with indexes and the such, would create the appropriate columns referencing what I am telling it to reference.

class UserRolesJoin < ActiveRecord::Migration
  def change
    create_table :xaaron_user_roles, id: false do |t|
      t.references :xaaron_user, null: false
      t.references :xaaron_role, null: false
    end

    add_index :xaaron_user_roles, :user_id
    add_index :xaaron_user_roles, [:role_id, :user_id], unique: true
    add_index :xarron_roles, :role, unique: true
  end
end

The exact error is:

 PG::UndefinedColumn: ERROR:  column "user_id" does not exist
: CREATE  INDEX  "index_xaaron_user_roles_on_user_id" ON "xaaron_user_roles"  ("user_id")/Users/Adam/.rvm/gems/ruby-2.0.0-p353/gems/activerecord-4.0.4/lib/active_record/connection_adapters/postgresql/database_statements.rb:128:in `async_exec'
/Users/Adam/.rvm/gems/ruby-2.0.0-p353/gems/activerecord-4.0.4/lib/active_record/connection_adapters/postgresql/database_statements.rb:128:in `block in execute''

Did I fail at typing something? Why is this migration failing, aside from the obvious?

Was it helpful?

Solution

If you just want to create a join table then,

1. Remove the existing migration

rails d migration UserRolesJoin

2. Create a new migration for join table as

rails g migration CreateJoinTableUserRole user role

This will create a migration like:

class CreateJoinTableUserRole < ActiveRecord::Migration
  def change
    create_join_table :users, :roles do |t|
      # t.index [:user_id, :role_id]
      # t.index [:role_id, :user_id]
    end
  end
end

NOTE: You need to uncomment one of the combination as per your requirement from the generated migration.

3. Run rake db:migrate

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top