我有用户和抗议表。用户可以制造抗议活动。 我想使用不同的名称“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
...
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
...
答案 0 :(得分:0)
尝试将迁移更改为:
t.references :creator, index: true, foreign_key: { to_table: :users }
相信这个答案:
答案 1 :(得分:0)
由于迁移中的这一行,您会看到user_id
:
t.references :user
要获得creator_id
,您可以使用integer
代替references
:
t.integer :creator_id