Ruby-on-rails 是否有 Rails 列类型的文档?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11889048/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 03:50:34  来源:igfitidea点击:

Is there documentation for the Rails column types?

ruby-on-rails

提问by Grant Birchmeier

I'm looking for more than the simple type listing that is found on this page:

我正在寻找的不仅仅是此页面上的简单类型列表:

:primary_key, :string, :text, :integer, :float, :decimal, :datetime, :timestamp, :time, :date, :binary, :boolean

:primary_key, :string, :text, :integer, :float, :decimal, :datetime, :timestamp, :time, :date, :binary, :boolean

But is there any documentation that actually definesthese fields?

但是是否有任何文档实际定义了这些字段?

Specifically:

具体来说:

  • What's the difference between :stringand :text?
  • Between :floatand :decimal?
  • What are the distinguishing features of :time, :timestamp, and :datetime?
  • :string和 和有:text什么区别?
  • :float和之间:decimal
  • 什么是显着特征:time:timestamp:datetime

Are the nuances of these types documented anywhere?

这些类型的细微差别是否记录在任何地方?

EDIT: Points of DB-platform implementations are irrelevant to the question I'm trying to ask.If, say, :datetimedoes not have a defined intended meaning in Rails documentation, then what do db-adapter-writers go by when choosing a corresponding column type?

编辑:DB 平台实现的要点与我要问的问题无关。例如,如果:datetime在 Rails 文档中没有定义的预期含义,那么 db-adapter-writers 在选择相应的列类型时会做什么?

回答by aguazales

Guidelines built from personal experience:

根据个人经验建立的指南:

  • String:
    • Limited to 255 characters (depending on DBMS)
    • Use for short text fields (names, emails, etc)
  • Text:
    • Unlimited length (depending on DBMS)
    • Use for comments, blog posts, etc. General rule of thumb: if it's captured via textarea, use Text. For input using textfields, use string.
  • Integer:
    • Whole numbers
  • Float:
    • Decimal numbers stored with floating point precision
    • Precision is fixed, which can be problematic for some calculations; generally no good for math operations due to inaccurate rounding.
  • Decimal:
    • Decimal numbers stored with precision that varies according to what is needed by your calculations; use these for math that needs to be accurate
    • See thispost for examples and an in-depth explanation on the differences between floats and decimals.
  • Boolean:
    • Use to store true/false attributes (i.e. things that only have two states, like on/off)
  • Binary:
    • Use to store images, movies, and other files in their original, raw format in chunks of data called blobs
  • :primary_key
    • This datatype is a placeholder that Rails translates into whatever primary key datatype your database of choice requires (i.e. serial primary keyin postgreSQL). Its use is somewhat complicated and not recommended.
    • Use model and migration constraints (like validates_uniqueness_ofand add_indexwith the :unique => trueoption) instead to simulate primary key functionality on one of your own fields.
  • Date:
    • Stores only a date (year, month, day)
  • Time:
    • Stores only a time (hours, minutes, seconds)
  • DateTime:
    • Stores both date and time
  • Timestamp
    • Stores both date and time
    • Note: For the purposes of Rails, both Timestamp and DateTime mean the same thing (use either type to store both date and time). For the TL;DR description of why both exist, read the bottom paragraph.
  • 字符串
    • 限制为 255 个字符(取决于 DBMS)
    • 用于短文本字段(姓名、电子邮件等)
  • 文字
    • 无限长度(取决于 DBMS)
    • 用于评论、博客文章等。一般经验法则:如果它是通过 textarea 捕获的,则使用 Text。对于使用文本字段的输入,请使用字符串。
  • 整数
    • 整数
  • 浮动
    • 以浮点精度存储的十进制数
    • 精度是固定的,这对于某些计算可能会有问题;由于四舍五入不准确,通常对数学运算没有好处。
  • 十进制
    • 以精确度存储的十进制数,根据您的计算需要而变化;将这些用于需要准确的数学
    • 有关浮点数和小数之间差异的示例和深入解释,请参阅帖子。
  • 布尔值
    • 用于存储真/假属性(即只有两种状态的事物,如开/关)
  • 二进制
    • 用于将图像、电影和其他文件以其原始原始格式存储在称为blob的数据块中
  • :首要的关键
    • 此数据类型是一个占位符,Rails 将其转换为您选择的数据库所需的任何主键数据类型(即serial primary key在 postgreSQL 中)。它的使用有些复杂,不推荐使用。
    • 使用模型和迁移约束(如validates_uniqueness_ofadd_index带有:unique => true选项)来模拟您自己的字段之一的主键功能。
  • 日期:
    • 仅存储日期(年、月、日)
  • 时间:
    • 仅存储时间(小时、分钟、秒)
  • 日期时间
    • 存储日期和时间
  • 时间戳
    • 存储日期和时间
    • 注意:就 Rails 而言,Timestamp 和 DateTime 的含义相同(使用任一类型来存储日期和时间)。对于 TL;DR 说明为什么两者都存在,请阅读底部段落。

These are the types about which confusion often exists; I hope this helps. I really don't know why there isn't official documentation about these. Also, I imagine these database adapters you referred to were written by the same people who wrote Rails, so they probably didn't need any documentation to go by when they were writing the adapters. Hope this helps!

这些是经常存在混淆的类型;我希望这有帮助。我真的不知道为什么没有关于这些的官方文档。此外,我认为您提到的这些数据库适配器是由编写 Rails 的同一个人编写的,因此他们在编写适配器时可能不需要任何文档。希望这可以帮助!

Note: the presence of both :DateTimeand :Timestamp, from what I can find, is included by Rails mostly for compatibility with database systems. For instance, MySQL's TIMESTAMPdatatype is stored as a unix timestamp. Its valid range goes from 1970 to 2038, and the time is stored as the number of seconds that have elapsed since the last epoch, which is supposedly standard, but in practice can differ from system to system. Recognizing that relative time was not a good thing to have in databases, MySQL later introduced the DATETIMEdatatype, which stores every digit in the year, month, day, hour, minute and second, at the cost of a size increase. The TIMESTAMPdatatype was retained for backwards compatibility. Other database systems went through similar evolutions. Rails recognized that multiple standards existed, and provided interfaces to both. However, Rails ActiveRecord defaults both :Timestampand :DateTimeto UTC dates stored in MySql's DATETIME, so it makes no functional difference to Rails programmers. These exist so that users who wishto differentiate between the two can do so. (For a more in-depth explanation, see thisSO answer).

注意:据我所知,Rails 包含:DateTimeand的存在:Timestamp主要是为了与数据库系统兼容。例如,MySQL 的TIMESTAMP数据类型存储为 unix 时间戳。它的有效范围从 1970 年到 2038 年,时间存储为自上一个纪元以来经过的秒数,这应该是标准的,但实际上可能因系统而异。认识到相对时间在数据库中并不是一件好事,MySQL 后来引入了DATETIME数据类型,它存储年、月、日、时、分和秒中的每个数字,但代价是大小增加。这TIMESTAMP保留数据类型是为了向后兼容。其他数据库系统也经历了类似的演变。Rails 认识到存在多种标准,并为两者提供了接​​口。但是,Rails ActiveRecord 默认:Timestamp:DateTimeUTC 日期存储在 MySql 的 中DATETIME,因此它对 Rails 程序员没有功能差异。这些存在以便希望区分两者的用户可以这样做。(有关更深入的解释,请参阅SO 答案)。

回答by fangxing

From Rails master branch souce code I found:

从 Rails 主分支源代码我发现:

abstract mysql_adapter

抽象 mysql_adapter

#activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb

  NATIVE_DATABASE_TYPES = {
    primary_key: "bigint auto_increment PRIMARY KEY",
    string:      { name: "varchar", limit: 255 },
    text:        { name: "text", limit: 65535 },
    integer:     { name: "int", limit: 4 },
    float:       { name: "float" },
    decimal:     { name: "decimal" },
    datetime:    { name: "datetime" },
    timestamp:   { name: "timestamp" },
    time:        { name: "time" },
    date:        { name: "date" },
    binary:      { name: "blob", limit: 65535 },
    boolean:     { name: "tinyint", limit: 1 },
    json:        { name: "json" },
  }

  # Maps logical Rails types to MySQL-specific data types.
  def type_to_sql(type, limit = nil, precision = nil, scale = nil, unsigned = nil)
    sql = case type.to_s
    when 'integer'
      integer_to_sql(limit)
    when 'text'
      text_to_sql(limit)
    when 'blob'
      binary_to_sql(limit)
    when 'binary'
      if (0..0xfff) === limit
        "varbinary(#{limit})"
      else
        binary_to_sql(limit)
      end
    else
      super(type, limit, precision, scale)
    end

    sql << ' unsigned' if unsigned && type != :primary_key
    sql
  end    

# and integer ...

  def integer_to_sql(limit) # :nodoc:
    case limit
    when 1; 'tinyint'
    when 2; 'smallint'
    when 3; 'mediumint'
    when nil, 4; 'int'
    when 5..8; 'bigint'
    else raise(ActiveRecordError, "No integer type has byte size #{limit}")
    end
  end

 # and text ..

  def text_to_sql(limit) # :nodoc:
    case limit
    when 0..0xff;               'tinytext'
    when nil, 0x100..0xffff;    'text'
    when 0x10000..0xffffff;     'mediumtext'
    when 0x1000000..0xffffffff; 'longtext'
    else raise(ActiveRecordError, "No text type has byte length #{limit}")
    end
  end

# and binary ...

    def binary_to_sql(limit) # :nodoc:
      case limit
      when 0..0xff;               "tinyblob"
      when nil, 0x100..0xffff;    "blob"
      when 0x10000..0xffffff;     "mediumblob"
      when 0x1000000..0xffffffff; "longblob"
      else raise(ActiveRecordError, "No binary type has byte length #{limit}")
      end
    end

the superin type_to_sqlmethod

supertype_to_sql方法

#activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb
  def type_to_sql(type, limit = nil, precision = nil, scale = nil) #:nodoc:
    type = type.to_sym if type
    if native = native_database_types[type]
      column_type_sql = (native.is_a?(Hash) ? native[:name] : native).dup

      if type == :decimal # ignore limit, use precision and scale
        scale ||= native[:scale]

        if precision ||= native[:precision]
          if scale
            column_type_sql << "(#{precision},#{scale})"
          else
            column_type_sql << "(#{precision})"
          end
        elsif scale
          raise ArgumentError, "Error adding decimal column: precision cannot be empty if scale is specified"
        end

      elsif [:datetime, :time].include?(type) && precision ||= native[:precision]
        if (0..6) === precision
          column_type_sql << "(#{precision})"
        else
          raise(ActiveRecordError, "No #{native[:name]} type has precision of #{precision}. The allowed range of precision is from 0 to 6")
        end
      elsif (type != :primary_key) && (limit ||= native.is_a?(Hash) && native[:limit])
        column_type_sql << "(#{limit})"
      end

      column_type_sql
    else
      type.to_s
    end
  end