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


当前回答

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

其他回答

String在数据库中翻译为“Varchar”,而text翻译为“text”。一个varchar可以包含更少的项,一个文本可以是(几乎)任何长度。

如需深入分析,请访问http://www.pythian.com/news/7129/text-vs-varchar/

编辑:一些数据库引擎可以一次性加载varchar,但将文本(和blob)存储在表之外。SELECT名称,amount FROM products使用text作为名称时比使用varchar时要慢得多。由于Rails,默认情况下使用SELECT * FROM…您的文本列将被加载。在你或我的应用程序中,这可能永远不会成为一个真正的问题(过早优化是…)。但知道文本并不总是“免费”是件好事。

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

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

用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作为较长的预期输入,如描述、评论内容等。

公认的答案是棒极了,它正确地解释了字符串和文本之间的区别(主要是数据库中的限制大小,但还有一些其他的陷阱),但我想指出一个小问题,让我通过它,因为这个答案并没有完全为我做。

最大大小: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

如果你使用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手册》