Thứ Năm, 11 tháng 9, 2014

Model - Các kiểu dữ liệu trong Database Table của Model trong Ruby on Rails

Ví dụ về cách tạo một Model tên Profile có các trường user_id, name, birthday, bio, color, twitter trong RoRs.
$ rails generate model Profile user_id:integer name:string birthday:date
bio:text color:string twitter:string


Ruby on Rails (ActiveRecord migration) hỗ trợ các loại dữ liệu (datatypes )sau đây:
  • :binary
  • :boolean
  • :date
  • :datetime
  • :decimal
  • :float
  • :integer
  • :primary_key
  • :references
  • :string
  • :text
  • :time
  • :timestamp
Giải thích chi tiết về các kiểu dữ liệu:
  • String:
    • Limited to 255 characters (depending on DBMS)
    • Use for short text fields (names, emails, etc)
  • Text:
    • Unlimited length
    • 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 this post 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)
  • :primary_key
    • This datatype is a placeholder that Rails translates into whatever primary key datatype your database of choice requires (i.e. serial primary key in postgreSQL). Its use is somewhat complicated and not recommended.
    • Use model and migration constraints (like validates_uniqueness_of and add_index with the:unique => true option) 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.

Không có nhận xét nào:

Đăng nhận xét