Rails 4: List of available datatypes
Here are all the Rails 4 (ActiveRecord migration) datatypes:
:binary
:boolean
:date
:datetime
:decimal
:float
:integer
:bigint
:primary_key
:references
:string
:text
:time
:timestamp
Source: http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html#method-i-add_column
These are the same as with Rails 3.
If you use PostgreSQL, you can also take advantage of these:
:hstore
:json
:jsonb
:array
:cidr_address
:ip_address
:mac_address
They are stored as strings if you run your app with a not-PostgreSQL database.
More PostgreSQL data types
- Rails 4
- Rails 5
- Rails 6
- Rails 7
Where is the documentation page for ActiveRecord data types?
If you're talking about the types for migrations, e.g. string, integer, datetime, etc, then you want ActiveRecord::ConnectionAdapters::TableDefinition, the column method. (Rails 5 edit: see also connection.add_column.)
As of this update, the standard types are:
:primary_key
:string
:text
:integer
:bigint
:float
:decimal
:numeric
:datetime
:time
:date
:binary
:boolean
The implementation of :decimal
is different with each database, so I'd avoid it if possible. You may use a type not in this list as long as it is supported by your database (for example, :polygon
in MySQL), but this will not be database agnostic and should also be avoided.
List of ActiveRecord DB datatypes as symbols/strings
You can use this command (run on an app using PG)
ActiveRecord::Base.connection.native_database_types.keys
# [:primary_key, :string, :text, :integer, :float, :decimal,
:datetime, :time, :date, :daterange, :numrange, :tsrange,
:tstzrange, :int4range, :int8range, :binary, :boolean, :xml,
:tsvector, :hstore, :inet, :cidr, :macaddr, :uuid, :json, :jsonb,
:ltree, :citext, :point, :line, :lseg, :box, :path, :polygon,
:circle, :bit, :bit_varying, :money]
Postgres:
You can also browse the source code and get this massive array.
https://github.com/rails/rails/blob/master/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb#L73-L114
NATIVE_DATABASE_TYPES = {
primary_key: "bigserial primary key",
string: { name: "character varying" },
text: { name: "text" },
integer: { name: "integer" },
float: { name: "float" },
decimal: { name: "decimal" },
datetime: { name: "timestamp" },
time: { name: "time" },
date: { name: "date" },
daterange: { name: "daterange" },
numrange: { name: "numrange" },
tsrange: { name: "tsrange" },
tstzrange: { name: "tstzrange" },
int4range: { name: "int4range" },
int8range: { name: "int8range" },
binary: { name: "bytea" },
boolean: { name: "boolean" },
xml: { name: "xml" },
tsvector: { name: "tsvector" },
hstore: { name: "hstore" },
inet: { name: "inet" },
cidr: { name: "cidr" },
macaddr: { name: "macaddr" },
uuid: { name: "uuid" },
json: { name: "json" },
jsonb: { name: "jsonb" },
ltree: { name: "ltree" },
citext: { name: "citext" },
point: { name: "point" },
line: { name: "line" },
lseg: { name: "lseg" },
box: { name: "box" },
path: { name: "path" },
polygon: { name: "polygon" },
circle: { name: "circle" },
bit: { name: "bit" },
bit_varying: { name: "bit varying" },
money: { name: "money" },
interval: { name: "interval" },
oid: { name: "oid" },
}
Mysql
https://github.com/rails/rails/blob/master/activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb#L41-L55
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" },
}
How to get list of available attributes using ActiveRecord enum Rails
Fruit.fruit_names
This will give you a ruby hash of the fruit names. Also your enum is wrong.
enum fruit_names: { banana: 0, apple: 1}
Enums are stored as an integer in the database so be careful with them. They are fantastic. You can also call:
Fruit.banana
That will return all the bananas objects.
Rails 4, has_many through, return a list of available items for a particular category
Both of your proposed solutions are valid, but let's look at some code:
Option 1 — Rails Defaults
resources :categories do
resources :items
end
# /categories/42/items/7
On its own, Rails would route this to the ItemsController
, which would be responsible for doing something with the category_id
that is passed in. If your application architecture/logic doesn't really ask to be done differently, I would start with this approach.
Option 2 — “Show a Category”
resources :categories, :items
class CategoriesController < ApplicationController
def index
@categories = Category.all
end
def show
@category = Category.includes(:items).find params[:id]
end
end
This approach is great if the notion of showing a controller would naturally show its items. This might not be appropriate in your case given the typical nature of many-to-many relationships, but it really depends on the context.
Option 3 — Three Tidy Controllers
If you find that your items#show
or items#index
methods are starting to get overly conditional, I would look into changing up your routing and adding a controller:
class CategorizedItemsController < ApplicationController
# ...
end
resources :categories
resources :items
scope '/categories/:category_id/' do
resources :items, controller: :categorized_items
end
This is less obvious to another developer joining your project, and starts to make reasoning about your routes a little more challenging, so I wouldn't begin with it. It's a great solution, though, and one that you shouldn't hesitate to adopt if you find your existing controller hierarchy failing to represent your actions within the bounds of RESTful routing.
Cheers!
Rails model with column that can represent multiple datatypes
Yes this can be done. Thanks to @dbugger, it is important to also remember to validate data stored in response
as well as use begin rescue blocks to protect against instances where the response
cannot be converted.
List of Rails Model Types
The attributes are SQL types, hence the following are supported:
:binary
:boolean
:date
:datetime
:decimal
:float
:integer
:primary_key
:string
:text
:time
:timestamp
These are documented under column in the Active Record API.
Related Topics
Code Block Passed to Each Works With Brackets But Not With 'Do'-'End' (Ruby)
Connecting Rails 3.1 With Multiple Databases
Executing Code For Every Method Call in a Ruby Module
How to Count Duplicate Elements in a Ruby Array
Pressing Ctrl + a in Selenium Webdriver
Understanding the "||" or Operator in If Conditionals in Ruby
Regular Expressions With Validations in Ror 4
Valid Email Address Regular Expression
Query , Can Not Select Column Count
How to Sum Array of Numbers in Ruby
How to Find and Return a Duplicate Value in Array
No Increment Operator (++) in Ruby
Why Does Installing Nokogiri on MAC Os Fail With Libiconv Is Missing
Group Hashes by Keys and Sum the Values