在Rails 5中运行迁移后,外键未正确更新

时间:2017-07-31 23:50:30

标签: ruby-on-rails ruby postgresql

我有用户和抗议表。用户可以制造抗议活动。 我想使用不同的名称“creator”将用户外键添加到Protests表。每当我运行我的迁移时,我希望在我的Protests表中看到creator_id,但我在schema.rb中看到了user_id。可能是什么原因?谢谢。

用户模型

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

抗议模型

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

抗议迁移

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

我在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

 ...

2 个答案:

答案 0 :(得分:0)

尝试将迁移更改为:

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

相信这个答案:

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

答案 1 :(得分:0)

由于迁移中的这一行,您会看到user_id

t.references :user

要获得creator_id,您可以使用integer代替references

t.integer :creator_id