1

I have Users and Protests tables. Users can create protests. I want to add user foreign key to Protests table with a different name "creator". Whenever I run my migrations, I expect to see creator_id in my Protests table, but I see user_id instead in my schema.rb. What could be the reason for that? Thank you.

User Model

class User < ApplicationRecord
devise :database_authenticatable, :registerable,
     :recoverable, :rememberable, :trackable, :validatable

validates :first_name, :last_name, :email,  presence: true

has_many :protests, foreign_key: :creator_id

has_many :attendances
has_many :attended_protests, through: :attendances, source: :protest

has_many :passengers
has_many :transportations, through: :passengers
end

Protest Model

class Protest < ApplicationRecord
validates :name, :description, :location,
        :starts_at, :creator, presence: true

has_attached_file :image, styles: {thumb: "100x100#", medium:"400x600#" }, default_url: "/images/default_:style_avatar.png"
validates_attachment_content_type :image, content_type: /\Aimage\/.*\Z/

belongs_to :creator, class_name: :User   

has_many :attendances
has_many :users, through: :attendances

has_many :transportations
end

Protests Migration

class CreateProtests < ActiveRecord::Migration[5.1]
def change
create_table :protests do |t|
   t.string :name
   t.text :description
   t.string :location
   t.datetime :starts_at
   t.references :user
 end
end
end

What I get in my schema.rb

 ...

create_table "protests", force: :cascade do |t|
 t.string "name"
 t.text "description"
 t.string "location"
 t.datetime "starts_at"
 t.bigint "user_id"
 t.string "image_file_name"
 t.string "image_content_type"
 t.integer "image_file_size"
 t.datetime "image_updated_at"
 t.index ["user_id"], name: "index_protests_on_user_id"
end

 ...
Mark
  • 13
  • 3
  • The root of this problem seems to be you have `t.references` in the migration file, and you want the column name to be different than the table name, which is the same as https://stackoverflow.com/questions/2933582/rails-migration-t-references-with-alternative-name – Simple Lime Aug 01 '17 at 00:12
  • 1
    Possible duplicate of [Rails migration: t.references with alternative name?](https://stackoverflow.com/questions/2933582/rails-migration-t-references-with-alternative-name) – Simple Lime Aug 01 '17 at 00:12

2 Answers2

0

Try changing you migration to:

t.references :creator, index: true, foreign_key: { to_table: :users }

credit to this answer:

https://stackoverflow.com/a/42056089/4553162

mahi-man
  • 4,326
  • 2
  • 25
  • 36
0

You see user_id because of this line in your migration:

t.references :user

To get creator_id you can use integer instead of references:

t.integer :creator_id
Gerry
  • 10,337
  • 3
  • 31
  • 40