在 Rails 中使用 add_reference 时如何使用 bigint 类型?

clo*_*oud 5 postgresql ruby-on-rails

在 Rails 5 和 PostgreSQL 中。

我创建此文件是为了使用bigint数据类型而不是integer默认情况:

# config/initializers/bigint_primary_keys.rb
ActiveRecord::ConnectionAdapters::PostgreSQLAdapter::NATIVE_DATABASE_TYPES[:primary_key] = 'bigserial primary key'
Run Code Online (Sandbox Code Playgroud)

因此,当运行 create 和 migrate 时,表 id 将被bigint键入。

# posts table
id bigint not null
...

# users table
id bigint not null
...
Run Code Online (Sandbox Code Playgroud)

add_reference但是在迁移中使用时:

class ChangeA < ActiveRecord::Migration[5]
  def change
    add_reference :posts, :users
  end
end
Run Code Online (Sandbox Code Playgroud)

posts添加该字段:

# posts table
...
user_id integer
Run Code Online (Sandbox Code Playgroud)

和表id都是poststype ,但是这个字段没有改变。usersbigint

有没有办法将数据类型设置为add_reference方法?

clo*_*oud 5

我找到了答案:

http://apidock.com/rails/ActiveRecord/ConnectionAdapters/SchemaStatements/add_reference

它有type选项。这就是我想要的。