rails 3/postgres - how long is a string if you don't apply :limit in schema

时光怂恿深爱的人放手 提交于 2019-12-22 02:05:40

问题


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 to VARCHAR(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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!