使用PostgreSQL适配器限制ActiveRecord迁移5.0中的文本列

the*_*ass 6 ruby postgresql ruby-on-rails rails-activerecord ruby-on-rails-5

我有一个看起来像这样的迁移

class CreateQuestionings < ActiveRecord::Migration[5.0]
  def change
    create_table :questionings do |t|
      t.text :body, null: false, limit: 260
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

现在,当我运行$ rake db:migrate:reset极限时,无处可见db/schema.rb:

create_table "questionings", force: :cascade do |t|
  t.text     "body",       null: false
end
Run Code Online (Sandbox Code Playgroud)

我做错了还是这个错误?

顺便说一句,我使用rails 5.0.0.beta3和ruby 2.3.0p0.

mu *_*ort 7

t.texttext在PostgreSQL中生成一个列,并且text不允许大小限制,因为text:

可变无限长度

由于数据库不支持限制,因此PostgreSQL驱动程序不会寻找:limit选项; 请记住,你说的t.text(column_name, options_hash)是你可以扔任何你想要的options_hash东西,司机会忽略任何不是特别寻找的东西.

如果要限制列大小,则可以手动添加CHECK约束(ActiveRecord将无法理解,因此您必须切换schema.rbstructure.sql)或使用varchar列(AKA t.string):

t.string :body, null: false, limit: 260
Run Code Online (Sandbox Code Playgroud)

此外,您schema.rb的生成基于数据库中的内容,而不是迁移中的内容.由于text不支持限制,数据库将不知道您的limit: 260选项; 如果数据库不知道它,当ActiveRecord向数据库询问架构信息时,ActiveRecord将不会从数据库中获取它.