我有 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/