我正在使用Rails制作一个新的web应用程序,想知道字符串和文本之间的区别是什么?什么时候分别使用?
当前回答
如果你使用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手册》
其他回答
较短的字段使用字符串,如姓名,地址,电话,公司
对于较大的内容、评论、内容、段落使用Text。
我的一般规则是,如果是超过一行的内容,我通常会选择文本,如果是2-6个简短的单词,我就会选择字符串。
对于字符串,官方规则是255。因此,如果字符串超过255个字符,请使用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
如果大小固定且较小,则为字符串;如果大小可变且较大,则为文本。 这很重要,因为文本比字符串大得多。它包含更多的千字节。
所以对于小字段总是使用string(varchar)。字段。First_name,登录名,电子邮件,(文章或帖子的)主题 文本的例子:一篇文章或文章的内容或主体。段落等字段
字符串大小从1到255(默认值为255)
文本大小1到4294967296(默认值为65536
公认的答案是棒极了,它正确地解释了字符串和文本之间的区别(主要是数据库中的限制大小,但还有一些其他的陷阱),但我想指出一个小问题,让我通过它,因为这个答案并没有完全为我做。
最大大小:limit => 1到4294967296不能完全按照放置的方式工作,我需要从最大大小到-1。我正在存储大型JSON blobs,有时它们可能非常大。
下面是我的迁移,使用了更大的值,MySQL不会抱怨这个值。
注意极限的末尾是5,而不是6
class ChangeUserSyncRecordDetailsToText < ActiveRecord::Migration[5.1]
def up
change_column :user_sync_records, :details, :text, :limit => 4294967295
end
def down
change_column :user_sync_records, :details, :string, :limit => 1000
end
end
如果属性在form中匹配f.text_field,则使用string,如果匹配f.text_area,则使用text。
推荐文章
- 如何在Ruby On Rails中使用NuoDB手动执行SQL命令
- ActiveRecord OR查询
- 无法安装gem -未能建立gem本地扩展-无法加载这样的文件——mkmf (LoadError)
- 在Rails中使用user_id:integer vs user:references生成模型
- 如何测试参数是否存在在轨道
- 验证多个列的唯一性
- Rails:在where语句中使用大于/小于
- Rails:如何为Rails activerecord的模型中的属性创建默认值?
- 库未加载:libmysqlclient.16。在OS X 10.6上使用mysql2 gem运行'rails server'时出现dylib错误
- 如何确定一个数组是否包含另一个数组的所有元素
- Rails find_or_create_by多个属性?
- Rails ActiveRecord日期之间
- 是什么导致这个ActiveRecord::ReadOnlyRecord错误?
- Rails:dependent =>:destroy VS:dependent =>:delete_all
- 对于PostgreSQL表来说,多大才算太大?