在 heroku 上的 PostgreSQL 数据库中存储超过 255 个字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4103141/
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
storing more than 255 characters in a PostgreSQL DB on heroku
提问by goddamnyouryan
I am using heroku, and in doing so, am experiencing my first foray into postgresql. Maybe I just never came across it in development, but I am unable to save entries into my database that are longer than 255 characters. Is there a way around this? Currently the I am just using strings to store message data.
我正在使用 heroku,这样做是我第一次涉足 postgresql。也许我只是在开发过程中从未遇到过它,但我无法将超过 255 个字符的条目保存到我的数据库中。有没有解决的办法?目前我只是使用字符串来存储消息数据。
Secondly, if there is indeed a way to store more than 255 characters, is there a good way to convert my message strings into this form, using migrations? My app is currently live and in use.
其次,如果确实有一种方法可以存储超过 255 个字符,是否有一种使用迁移将我的消息字符串转换为这种形式的好方法?我的应用程序目前正在使用中。
Thanks!
谢谢!
回答by thenengah
use text
instead of string
on your migration type.
在您的迁移类型上使用text
而不是string
。
To change a migration
更改迁移
script/generate migration change_string_to_text
change_column :model, :attribute, :text
rake db:migrate
script/generate migration change_string_to_text
change_column :model, :attribute, :text
rake db:migrate
回答by Noach Magedman
Just to expand on @Codeglot's answer, :text
is for (essentially) unlimited-length strings. :string
with a limit:1234
option will limit the string to that length. On Postgres, a :string, limit:nil
is effectively synonymous with :text
. Although some databases store VARCHAR, VARCHAR(n), and TEXT types in different ways, leading to performance considerations, Postgres stores them all in the same way.
只是为了扩展@Codeglot 的答案,:text
适用于(基本上)无限长度的字符串。 :string
带有limit:1234
选项会将字符串限制为该长度。在 Postgres 上, a:string, limit:nil
实际上是:text
. 尽管一些数据库以不同的方式存储 VARCHAR、VARCHAR(n) 和 TEXT 类型,导致性能方面的考虑,但 Postgres 以相同的方式存储它们。
So if you want to exceed 255 chars but not be completelyunbounded, you can use :string, limit:1234
. Alternatively, you can use :text
and restrict the length via validations.
因此,如果您想超过 255 个字符但又不想完全无限制,则可以使用:string, limit:1234
. 或者,您可以:text
通过验证使用和限制长度。