SQL Rails:用于创建固定长度 char(12) 列的迁移

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5536444/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 10:00:54  来源:igfitidea点击:

Rails : migration for creating a fixed-length char(12) column

sqlruby-on-railsrails-migrations

提问by manu_v

What is the best way to define a fixed-length SQL column (CHAR(12) for instance) through a Rails migration ?

通过 Rails 迁移定义固定长度的 SQL 列(例如 CHAR(12))的最佳方法是什么?

Why this should not handled by the model is because of the performance of char() vs varchar(), and I'd like to avoid injecting raw SQL in the database.

为什么这不应该由模型处理是因为 char() 与 varchar() 的性能,我想避免在数据库中注入原始 SQL。

Edit : I know the :limit modifier, however the field is still varchar (which is bad for performance) and does not allow a minimum size.

编辑:我知道 :limit 修饰符,但是该字段仍然是 varchar (这对性能不利)并且不允许最小大小。

回答by KenB

If Rails doesn't understand the column type, it'll pass it straight through to the database. So if you want a char instead of varchar, just replace:

如果 Rails 不理解列类型,它会直接将它传递给数据库。所以如果你想要一个字符而不是 varchar,只需替换:

t.column :token, :string

With:

和:

t.column :token, "char(12)"

Of course, this may or may not make your migrations non-portable to another database.

当然,这可能会也可能不会使您的迁移无法移植到另一个数据库。

(credit to http://laurelfan.com/2010/1/26/special-mysql-types-in-rails-migrations)

(归功于http://laurelfan.com/2010/1/26/special-mysql-types-in-rails-migrations

回答by demas

 def self.up
    add_column("admin_users", "username", :string, :limit => 25)
 end

 def self.down
    remove_column("admin_users", "username")
 end

回答by Ashish

You can use string type with limit option in your migration file like this:

您可以在迁移文件中使用带有限制选项的字符串类型,如下所示:

t.string :name, :limit => 12, :null => false

回答by meoww-

For a database specific type, we can now use:

对于特定于数据库的类型,我们现在可以使用:

t.column(:column_name, 'char(12)')

And for a complete example:

对于一个完整的例子:

class Foo < ActiveRecord::Migration
  def change
     create_table :foo do |t|
       t.column(:column_name, 'custom_type')

       t.timestamps
     end
  end
end