问题
My googlefu must be weak because I cannot find anything to tell me the default limit of a string column in my Rails app (hosted at Heroku, using PostgreSQL as the database).
Any help would be appreciated!
回答1:
ActiveRecord uses varchar(255)
(or character varying (255)
to be pedantic) if you don't specify a specific limit. You can always hop into PostgreSQL with psql
and say \d your_table
to get the table as PostgreSQL sees it.
I don't think the default is specified anywhere but it is right here in the source:
NATIVE_DATABASE_TYPES = {
:primary_key => "serial primary key",
:string => { :name => "character varying", :limit => 255 },
#...
The closest thing to a specification is in the Migrations Guide:
These will be mapped onto an appropriate underlying database type, for example with MySQL
:string
is mapped toVARCHAR(255)
.
But that's not about PostgreSQL and not exactly a guarantee.
As an aside, if you're using PostgreSQL, you should almost always go straight to :text
and pretend that :string
doesn't exist. PostgreSQL treats them the same internally except that it has to do a length check on varchar
. There's a bit more discussion on this over here in another one of my answers: Changing a column type to longer strings in rails.
回答2:
In rails 4 there is no default limit for string type as you can see in the source:
NATIVE_DATABASE_TYPES = {
primary_key: "serial primary key",
bigserial: "bigserial",
string: { name: "character varying" },
text: { name: "text" },
#...
if you don't specify a limit ActiveRecord will just set character varying
and you could store there a string of any length as stated in the documentation:
If character varying is used without length specifier, the type accepts strings of any size
来源:https://stackoverflow.com/questions/8129776/rails-3-postgres-how-long-is-a-string-if-you-dont-apply-limit-in-schema