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

标签 ruby-on-rails ruby postgresql

我有 Users 和 Protests 表。用户可以发起抗议。 我想将用户外键添加到具有不同名称“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

 ...

最佳答案

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

t.references :user

要获取 creator_id,您可以使用 integer 而不是 references:

t.integer :creator_id

关于ruby-on-rails - 在 Rails 5 中运行迁移后,外键未正确更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45426927/

相关文章:

ruby-on-rails - 替换 ActiveRecord 5 中的 ActiveRecord::ConnectionAdapters::ConnectionManagement

ruby-on-rails - Twitter Bootstrap 和 Spree 项目?

ruby - Selenium Ruby Webdriver - 如何关闭显示弹出窗口的 IE9 浏览器 session

postgresql - 为什么 Postgres 不在简单的 ORDER BY LIMIT 1 上使用我的索引?

database - 错误 : no PostgreSQL user name specified in startup packet

javascript - 在disable_with之后禁用按钮

ruby-on-rails - 如何在 Ruby on Rails 中读取基于编码的 CSV

ruby - RobuSTLy 调用不稳定的 API:使用 Net::HTTP 进行正确的错误处理

html - 使用 Ruby 和 Selenium Webdriver find_elements 根据条件选择并单击特定链接

postgresql - 在 Sequelize 中为 Postgres 使用事务