ruby-on-rails - Activerecord 迁移,使 t.references 正确指向自定义 ID 类型,字符串而不是整数?

标签 ruby-on-rails ruby activerecord migration

下面我有一个“测试”模型的迁移,它使用它自己的主键,一个字符串而不是一个整数。

    class CreateTest < ActiveRecord::Migration[5.1]
      def change
        create_table :test, id: false do |t|

          t.string  :id,          primary_key: true

          t.timestamps
        end        
      end
    end

现在我们有了 t.references 测试的“客户端”模型。

    class CreateClients < ActiveRecord::Migration[5.1]
      def change
        create_table :clients do |t|

          t.references :test,   null: false

          t.timestamps
        end
      end
    end

问题是 t.references 假定它是一个整数 id。

    # == Schema Information
    #
    # Table name: clients
    #
    #  id         :integer          not null, primary key
    #  test_id    :integer          not null
    #  created_at :datetime         not null
    #  updated_at :datetime         not null

这显然是错误的,因为 Test.id 是一个字符串。

我需要施展魔法才能让 t.references “知道”它是一个基于模型或其他东西的字符串吗?

谢谢。

最佳答案

使用 references 将其添加到迁移中:

type: :string

The reference column type. Defaults to :integer.

You can read more here.

关于ruby-on-rails - Activerecord 迁移,使 t.references 正确指向自定义 ID 类型,字符串而不是整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49430757/

相关文章:

ruby-on-rails - 在Rails 4.2.4中的 Controller 中使用助手

javascript - Rails js 文件和页面特定的 js

ruby-on-rails - rails : AND operator in a has_many association

ruby-on-rails - 将两个 ActiveRecord::Relation 与 OR 组合,而不是 AND,返回一个 Relation 而不是一个 Array 以便以后能够分页

ruby-on-rails - 如何使用 Mongoid 更新 Rails 中嵌套的 Mongo 文档属性?

javascript - 从 Rails 应用程序访问 HTML5 本地存储

ruby-on-rails - 运行 "rails server"后如何使用 Rails 控制台

ruby - 使用 Ruby Mechanize 提交 'aspnetForm' 未按预期工作

ruby-on-rails - 'compass watch' 是如何工作的/它是如何与 rails 一起使用的

ruby-on-rails - 我如何在 select in rails 中编写查询