【问题标题】:Specify column name in create_table in Rails migration belongs_to column在 Rails 迁移 belongs_to 列的 create_table 中指定列名
【发布时间】:2018-06-25 09:34:35
【问题描述】:

我正在创建下表:

create_table(:categories) do |t|
  t.belongs_to :user, null: false, foreign_key: true, index: true
  t.uuid :uuid, unique: true, null: true, index: true
  t.string :kind, :limit => 32, null: false, index: true
  t.string :category, null: false, index: true
  t.datetime :deleted_at, null: true, index: true
  t.timestamps null: false, index: false

  t.index [:kind, :category], :unique => true
end

第一列是外键,默认命名为“user_id”。我想用belongs_to 创建列,但将列名指定为“created_by_user_id”。我该怎么做?

【问题讨论】:

    标签: ruby-on-rails migration rails-migrations


    【解决方案1】:

    您可以像这样将外键列的名称传递给foreign_key

    create_table(:categories) do |t|
      t.belongs_to :user, null: false, foreign_key: 'created_by_user_id', index: true
      ...
    end
    

    【讨论】:

    • 奇怪的是这对我不起作用。它仍然将列名创建为 user_id。 Rails 4.2.10
    • 尝试在t.belongs_to之后添加这一行:add_foreign_key :categories, :users, column: :created_by_user_id,按照这个答案:stackoverflow.com/a/29577869/5636930
    【解决方案2】:

    我猜您正在寻找的解决方案是明确创建 intbigint 列,具体取决于您的数据库。

    所以它会是这样的:

    create_table(:categories) 做 |t| t.integer :created_by_user_id, null: false, foreign_key: true, index: true ...

    【讨论】:

    • Users表上的user_id如何指定foreign_key?
    • Rails 通过 belongs_to 内部模型执行此操作。 belongs_to :user, foreign_key: "created_by_user_id"
    猜你喜欢
    • 2012-11-21
    • 2016-03-08
    • 1970-01-01
    • 2012-05-25
    • 2019-03-26
    • 2016-12-02
    • 2010-09-27
    • 2013-12-14
    • 2016-05-28
    相关资源
    最近更新 更多