我正在使用Rails制作一个新的web应用程序,想知道字符串和文本之间的区别是什么?什么时候分别使用?


当前回答

较短的字段使用字符串,如姓名,地址,电话,公司

对于较大的内容、评论、内容、段落使用Text。

我的一般规则是,如果是超过一行的内容,我通常会选择文本,如果是2-6个简短的单词,我就会选择字符串。

对于字符串,官方规则是255。因此,如果字符串超过255个字符,请使用text。

其他回答

如上所述,不只是db数据类型,它也会影响将生成的视图,如果你是脚手架。 String将生成一个text_field text将生成一个text_area

如果属性在form中匹配f.text_field,则使用string,如果匹配f.text_area,则使用text。

如果你正在使用oracle…STRING将被创建为VARCHAR(255)列,TEXT将被创建为CLOB。

NATIVE_DATABASE_TYPES = {
    primary_key: "NUMBER(38) NOT NULL PRIMARY KEY",
    string: { name: "VARCHAR2", limit: 255 },
    text: { name: "CLOB" },
    ntext: { name: "NCLOB" },
    integer: { name: "NUMBER", limit: 38 },
    float: { name: "BINARY_FLOAT" },
    decimal: { name: "DECIMAL" },
    datetime: { name: "TIMESTAMP" },
    timestamp: { name: "TIMESTAMP" },
    timestamptz: { name: "TIMESTAMP WITH TIME ZONE" },
    timestampltz: { name: "TIMESTAMP WITH LOCAL TIME ZONE" },
    time: { name: "TIMESTAMP" },
    date: { name: "DATE" },
    binary: { name: "BLOB" },
    boolean: { name: "NUMBER", limit: 1 },
    raw: { name: "RAW", limit: 2000 },
    bigint: { name: "NUMBER", limit: 19 }
}

https://github.com/rsim/oracle-enhanced/blob/master/lib/active_record/connection_adapters/oracle_enhanced_adapter.rb

如果你使用postgres,尽可能使用文本,除非你有大小限制,因为文本vs varchar没有性能损失

There is no performance difference among these three types, apart from increased storage space when using the blank-padded type, and a few extra CPU cycles to check the length when storing into a length-constrained column. While character(n) has performance advantages in some other database systems, there is no such advantage in PostgreSQL; in fact character(n) is usually the slowest of the three because of its additional storage costs. In most situations text or character varying should be used instead

PostsgreSQL手册》

区别在于如何将符号转换为查询语言中相应的列类型。

用MySQL:字符串映射到VARCHAR https://edgeguides.rubyonrails.org/active_record_migrations.html

:string |                   VARCHAR                | :limit => 1 to 255 (default = 255)  
:text   | TINYTEXT, TEXT, MEDIUMTEXT, or LONGTEXT2 | :limit => 1 to 4294967296 (default = 65536)

参考:

https://hub.packtpub.com/working-rails-activerecord-migrations-models-scaffolding-and-database-completion/

什么时候分别使用?

一般的经验法则是,使用:string作为短文本输入(用户名、电子邮件、密码、标题等),使用:text作为较长的预期输入,如描述、评论内容等。