cheatsheets/rails-migrations.html

337 lines
9.3 KiB
HTML
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<!doctype html>
<html lang='en' class='no-js '>
<head>
<meta charset='utf-8'>
<meta content='width=device-width, initial-scale=1.0' name='viewport'>
<link href='./assets/favicon.png' rel='shortcut icon'>
<meta content='/rails-migrations.html' name='app:pageurl'>
<title>Migrations cheatsheet</title>
<meta content='Migrations cheatsheet' property='og:title'>
<meta content='Migrations cheatsheet' property='twitter:title'>
<meta content='article' property='og:type'>
<meta content='https://assets.devhints.io/previews/rails-migrations.jpg?t=20211021033128' property='og:image'>
<meta content='https://assets.devhints.io/previews/rails-migrations.jpg?t=20211021033128' property='twitter:image'>
<meta content='900' property='og:image:width'>
<meta content='471' property='og:image:height'>
<meta content="The one-page guide to Migrations: usage, examples, links, snippets, and more." name="description">
<meta content="The one-page guide to Migrations: usage, examples, links, snippets, and more." property="og:description">
<meta content="The one-page guide to Migrations: usage, examples, links, snippets, and more." property="twitter:description">
<link rel="canonical" href="https://devhints.io/rails-migrations">
<meta name="og:url" content="https://devhints.io/rails-migrations">
<meta content='Devhints.io cheatsheets' property='og:site_name'>
<meta content='Rails' property='article:section'>
<script async src='https://www.googletagmanager.com/gtag/js?id=UA-106902774-1'></script>
<script>
window.dataLayer=window.dataLayer||[];
function gtag(){dataLayer.push(arguments)};
gtag('js',new Date());
gtag('config','UA-106902774-1');
</script>
<meta property='page:depth' content='1'>
<script>(function(H){H.className=H.className.replace(/\bno-js\b/,'js')})(document.documentElement)</script>
<script>(function(H){H.className=H.className.replace(/\bNoJs\b/,'WithJs')})(document.documentElement)</script>
<script>(function(d,s){if(window.Promise&&[].includes&&Object.assign&&window.Map)return;var js,sc=d.getElementsByTagName(s)[0];js=d.createElement(s);js.src='https://cdn.polyfill.io/v2/polyfill.min.js';sc.parentNode.insertBefore(js, sc);}(document,'script'))</script>
<!--[if lt IE 9]><script src='https://cdnjs.cloudflare.com/ajax/libs/nwmatcher/1.2.5/nwmatcher.min.js'></script><script src='https://cdnjs.cloudflare.com/ajax/libs/json2/20140204/json2.js'></script><script src='https://cdn.rawgit.com/gisu/selectivizr/1.0.3/selectivizr.js'></script><script src='https://cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7.3/html5shiv.min.js'></script><script src='https://cdnjs.cloudflare.com/ajax/libs/respond.js/1.4.2/respond.js'></script><![endif]-->
<style>html{opacity:0}</style>
<link rel="stylesheet" href="./assets/2015/style.css?t=20211021033128">
<link href="./assets/style.css?t=20211021033128" rel="stylesheet" />
<link href="./assets/print.css?t=20211021033128" rel="stylesheet" media="print" />
</head>
<body>
<div class='all'>
<div class='site-header'>
<div class='container'>
This is <a href="."><em>Devhints.io cheatsheets</em></a> &mdash; a collection of cheatsheets I've written.
</div>
</div>
<script type='application/ld+json'>
{
"@context": "http://schema.org",
"@type": "NewsArticle",
"mainEntityOfPage": {
"@type": "WebPage",
"@id": "https://google.com/article"
},
"headline": "Migrations cheatsheet",
"image": [ "https://assets.devhints.io/previews/rails-migrations.jpg?t=20211021033128" ],
"description": "The one-page guide to Migrations: usage, examples, links, snippets, and more."
}
</script>
<script type='application/ld+json'>
{
"@context": "http://schema.org",
"@type": "BreadcrumbList",
"itemListElement": [{
"@type": "ListItem",
"position": 1,
"item": {
"@id": "https://devhints.io/#rails",
"name": "Rails"
}
},{
"@type": "ListItem",
"position": 2,
"item": {
"@id": "https://devhints.io/rails-migrations",
"name": "Migrations"
}
}]
}
</script>
<div class='post-list -single -cheatsheet'>
<div class='post-item'>
<div class='post-headline -cheatsheet'>
<p class='prelude'><span></span></p>
<h1><span>Migrations</span></h1>
<div class='pubbox'>
<div class='HeadlinePub' role='complementary'>
<script async src='https://pubsrv.devhints.io/carbon.js?serve=CE7IK5QM&placement=devhintsio&cd=pubsrv.devhints.io/s' id="_carbonads_js"></script>
<span class='placeholder -one'></span>
<span class='placeholder -two'></span>
<span class='placeholder -three'></span>
<span class='placeholder -four'></span>
</div>
</div>
</div>
<div class='post-content -cheatsheet'>
<h3 id="automatically-make-migrations">Automatically make migrations</h3>
<pre><code>$ rails generate migration RemovePartNumberFromProducts part_number:string
$ rails generate migration remove_part_number_from_products part_number # rails assumes string if not type given - and you can use snake_case
$ rails generate migration AddNameToWidgets name:string
$ rails g migration add_name_to_widgets name:string # you can use the short cut 'g' instead of generate - they both do the same thing
</code></pre>
<h3 id="run-migrations">Run migrations</h3>
<pre><code>$ rake db:migrate
</code></pre>
<h3 id="creating-tables">Creating tables</h3>
<pre><code>create_table :users do |t|
t.string :name
t.text :description
t.primary_key :id
t.string :title
t.text :description
t.integer :games_count
t.float :lol
t.decimal :price
t.decimal :price, :precision =&gt; 2, :scale =&gt; 10
t.datetime :expiration
t.timestamp :time_in
t.time :time_in
t.date :expiry
t.binary :image_data
t.boolean :is_admin
end
# Options:
:null (boolean)
:limit (integer)
:default
</code></pre>
<h3 id="operations">Operations</h3>
<pre><code>add_column :users, :first_name, :string
remove_column :users, :first_name, :string
change_column :users, :first_name, :text
change_column_default :users, :admin, nil
change_column_null :users, :email, false # adds NOT NULL constraint
create_table
change_table
drop_table
add_column
change_column
rename_column
remove_column
add_index
remove_index
</code></pre>
<h3 id="use-models">Use models</h3>
<pre><code>class AddFlagToProduct &lt; ActiveRecord::Migration
class Product &lt; ActiveRecord::Base
end
def change
add_column :products, :flag, :boolean
Product.reset_column_information
reversible do |dir|
dir.up { Product.update_all flag: false }
end
end
end
</code></pre>
<h3 id="associations">Associations</h3>
<pre><code>t.references :category # kinda same as t.integer :category_id
# Can have different types
t.references :category, polymorphic: true
</code></pre>
<h3 id="auto-addremove-columns">Auto-Add/remove columns</h3>
<pre><code>$ rails generate migration RemovePartNumberFromProducts part_number:string
</code></pre>
<h3 id="indices">Indices</h3>
<pre><code># Simple
add_index :suppliers, :name
# Unique
add_index :accounts, [:branch_id, :party_id], :unique =&gt; true
# Named (:name =&gt; ...)
add_index :accounts, [:branch_id, :party_id], :unique =&gt; true, :name =&gt; "by_branch_party"
# Length
add_index :accounts, :name, :name =&gt; by_name, :length =&gt; 10
add_index :accounts, [:name, :surname], :name =&gt; by_name_surname,
:length =&gt; {
:name =&gt; 10,
:surname =&gt; 15
}
# Sort order (no MySQL support)
add_index :accounts, [:branch_id, :party_id, :surname],
:order =&gt; {:branch_id =&gt; :desc, :part_id =&gt; :asc}
</code></pre>
<h3 id="in-console">In console</h3>
<p>Use <code>ActiveRecord::Migration</code>.</p>
<pre><code>ActiveRecord::Migration.add_index :posts, :slug
</code></pre>
<h3 id="references">References</h3>
<ul>
<li>http://apidock.com/rails/ActiveRecord/ConnectionAdapters/SchemaStatements/add_index</li>
</ul>
</div>
<ul class="social-list ">
<li class="facebook link hint--bottom" data-hint="Share on Facebook"><a href="https://www.facebook.com/sharer/sharer.php?u=https://devhints.io/rails-migrations.html" target="share"><span class="text"></span></a></li>
<li class="twitter link hint--bottom" data-hint="Share on Twitter"><a href="https://twitter.com/intent/tweet?text=The%20ultimate%20cheatsheet%20for%20Migrations.%20https://devhints.io/rails-migrations.html" target="share"><span class="text"></span></a></li>
</ul>
</div>
</div>
<div class="about-the-site">
<div class="container">
<p class='blurb'>
<strong><a href=".">Devhints.io cheatsheets</a></strong> is a collection of cheatsheets I've written over the years.
Suggestions and corrections? <a href='https://github.com/rstacruz/cheatsheets/issues/907'>Send them in</a>.
<i class='fleuron'></i>
I'm <a href="http://ricostacruz.com">Rico Sta. Cruz</a>.
Check out my <a href="http://ricostacruz.com/til">Today I learned blog</a> for more.
</p>
<p class='back'>
<a class='big-button -back -slim' href='.#toc'></a>
</p>
<p>
</p>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/8.5/highlight.min.js"></script>
<script src="https://cdn.rawgit.com/rstacruz/unorphan/v1.0.1/index.js"></script>
<script>hljs.initHighlightingOnLoad()</script>
<script>unorphan('h1, h2, h3, p, li, .unorphan')</script>
</body>
</html>