Rails Cheatsheet

Bold words are what is really important e.g. the command and concept shown in the usage category. In the code usage and example columns these highlight the main part of the concept, like this: general_stuff.concept. In the same columns italic_words mark the arguments/parameters of a command/method.

However italic words in the descriptions or general text denote more general concepts or concepts explained elsewhere in this cheat sheet or in general.

The console (also called command line, command prompt or terminal) is just another way of interacting with your computer. So you can basically do anything with it that you could also do with your graphical desktop user interface. This sections contains a couple of examples.

For the different operating systems starting the console differs.

  • Windows: Open the start menu and search for command prompt. Alternatively choose execute and enter cmd.
  • Mac: Open Spotlight, type terminal, and start that program.
  • Linux: The terminal should be one of the main options once you open the main menu of your distribution. Otherwise search for terminal if your distribution has such an option or look under Accessories.
ConceptUsageExamplesDescription
Change directorycddirectory

cd my_app

cd my_app/app/controllers

Changes the directory to the specified directory on the console.
List contents directory

lsdirectory

Windows: dirdirectory

ls

lsmy_app

Shows all contents (files and folders) of the directory. If no directory is specified shows the contents of the current directory.
Directory you are currently inpwdpwdShows the full path of the directory you are currently in. E.g. /home/tobi/railsgirls
A note on filenames: if a file or directory name starts with a slash / as in the output of pwd above, it is an absolute filename specifying the complete filename starting at the root of the current file system (e.g. hard disk). If the slash (/) is omitted, the file name is relative to the current working directory.
Create a new directorymkdirname

mkdirrails

mkdirfun

Creates a directory with the given name in the folder you are currently in.
Delete a file

rmfile

Windows: delfile

rmfoo

rmindex.html

rmpictures/old_picture.jpg

Deletes the specified file. Be extra cautious with this as it would be too bad to delete something you still need :-(

You can simply specify the name of a file of the directory you are currently in. However you can also specify a path, this is shown in the third example. There we delete the old_picture.jpg file from the pictures folder.

Delete a directory

rm -rfolder

Windows: rdfolder

rm -rstuff_i_dont_need

rm -rstuff_i_dont_need/

rm -rold_application

Deletes the specified folder and all of its contents. So please be super cautious with this! Make sure that you do not need any of the contents of this folder any more.

So why would you want to delete a whole folder? Well maybe it was an old application that you do not need anymore :-)

Starting a programprogramarguments

firefox

firefoxrailsgirlsberlin.de

irb

Starts the program with the given name and arbitrary arguments if the program takes arguments. Firefox is just one example. Starting Firefox without arguments just opens up Firefox. If you give it an argument it opens the specified URL. When you type in irb this starts interactive ruby.
Abort the programPress Ctrl + C-This will abort the program currently running in the terminal. For instance this is used to shut down the Rails server. You can also abort many other related tasks with it, including: bundle install, rake db:migrate, git pull and many more!

Ruby is the programming language Ruby on Rails is written in. So most of the time you will be writing Ruby code. Therefore it is good to grasp the basics of Ruby. If you just want to play with Ruby, type irb into your console to start interactive ruby. There you can easily experiment with Ruby. To leave irb, type exit.

This is just a very small selection of concepts. This is especially true later on when we talk about what Arrays, Strings etc. can do. For more complete information have a look at ruby-doc or search with your favorite search engine!

The one-page guide to Rails models: usage, examples, links, snippets, and more. Devhints.io Edit; Rails models cheatsheet. Generating Generating. Other Rails cheatsheets. Arel cheatsheet Controllers cheatsheet Form helpers cheatsheet Helpers cheatsheet i18n cheatsheet Migrations cheatsheet Top cheatsheets. Elixir cheatsheet. Last week I wrote about making a Ruby and Rails course, and some of the lessons I learned in the process. One of the biggest lessons that I learned was that Ruby and Rails is way too much for a single session. Part of that pain came from the Rails cheat sheet created for the course because it was missing a lot of key information about Rails. We liked the idea of limiting the sheet to a single. RSpec Rails Examples. An RSpec cheatsheet in the form of a Rails app. Learn how to expertly test Rails apps from a model codebase. A small yet comprehensive reference for developers who want to know how to test Rails apps using RSpec. Ruby on Rails Cheatsheet (5.1) Architecture. RVM $ rvm list - show currently installed Rubies $ rvm install 2.3.1 $ rvm use -default 2.3.1 - use most recent. Create a new application. Install the Rails gem if you haven't done so before $ gem install rails Generate a new Rails app w/ Postgres support $ bin/rails new myapp -database=postgresql.

General concepts

ConceptUsageExamplesDescription
Comment#Comment text

#This text is a comment

some.ruby_code # A comment

# some.ignored_ruby_code

Ruby ignores everything that is marked as a comment. It does not try to execute it. Comments are just there for you as information. Comments are also commonly used to comment out code. That is when you don't want some part of your code to execute but you don't want to delete it just yet, because you are trying different things out.
Variablesvariable =some_value With a variable you tell Ruby that from now on you want to refer to that value by the name you gave it. So for the first example, from now on when you use name Ruby will know that you meant 'Tobi'.
Console outputputssomething

puts'Hello World'

puts[1, 5, 'mooo']

Prints its argument to the console. Can be used in Rails apps to print something in the console where the server is running.
Call a methodobject.method(arguments)

string.length

array.delete_at(2)

string.gsub('ae', 'ä')

Calling a method is also often referred to as sending a message in Ruby. Basically we are sending an object some kind of message and are waiting for its response. This message may have no arguments or multiple arguments, depending on the message. So we kindly ask the object to do something or give us some information. When you 'call a method' or 'send a message' something happens. In the first example we ask a String how long it is (how many characters it consists of). In the last example we substitute all occurrences of 'ae' in the string with the German 'ä'.

Different kinds of objects (Strings, Numbers, Arrays..) understand different messages.

Define a method

Methods are basically reusable units of behaviour. And you can define them yourself just like this. Methods are small and focused on implementing a specific behaviour.

Our example method is focused on greeting people. You could call it like this: greet('Tobi')

Equalityobject other

true true # => true

3 4 # => false

'Hello' 'Hello' # => true

'Helo' 'Hello' # => false

With two equal signs you can check if two things are the same. If so, true will be returned; otherwise, the result will be false.
Inequalityobject != other

true != true # => false

3 != 4 # => true

Inequality is the inverse to equality, e.g. it results in true when two values are not the same and it results in false when they are the same.
Decisions with if

With if-clauses you can decide based upon a condition what to do. When the condition is considered true, then the code after it is executed. If it is considered false, the code after the 'else' is executed.

In the example, access is granted based upon the decision if a given input matches the password.

ConstantsCONSTANT =some_value Constants look like variables, just in UPCASE. Both hold values and give you a name to refer to those values. However while the value a variable holds may change or might be of an unknown value (if you save user input in a variable) constants are different. They have a known value that should never change. Think of it a bit like mathematical or physical constants. These don't change, they always refer to the same value.

Numbers

Numbers are what you would expect them to be, normal numbers that you use to perform basic math operations.

More information about numbers can be found in the ruby-doc of Numeric.

ConceptUsageExamplesDescription
normal Numbernumber_of_your_choice

0

-11

42

Numbers are natural for Ruby, you just have to enter them!
Decimalsmain.decimal

Clion external library. 3.2

-5.0

You can achieve decimal numbers in Ruby simply by adding a point.
Basic Mathn operatorm

2 +3 # => 5

5 -7 # => -2

8 *7 # => 56

84 /4 # => 21

In Ruby you can easily use basic math operations. In that sense you may use Ruby as a super-powered calculator.
Comparisonn operatorm

12 >3 # => true

12 <3 # => false

7 >=7 # => true

Numbers may be compared to determine if a number is bigger or smaller than another number. When you have the age of a person saved in the age variable you can see if that person is considered an adult in Germany:

age >= 18 # true or false

Strings

Strings are used to hold textual information. They may contain single characters, words, sentences or a whole book. However you may just think of them as an ordered collection of characters.

You can find out more about Strings at the ruby-doc page about Strings.

ConceptUsageExamplesDescription
Create

'A string'

'Hello World'

'a'

'Just characters 129 _!$%^'

'

A string is created by putting quotation marks around a character sequence. A Ruby style guide recommends using single quotes for simple strings.
Interpolation

'A string and an #{expression}'

'Email: #{user.email}'

'The total is #{2 + 2}'

'A simple string'

You can combine a string with a variable or Ruby expression using double quotation marks. This is called 'interpolation.' It is okay to use double quotation marks around a simple string, too.
Lengthstring.length

'Hello'.length # => 5

'.length # => 0

You can send a string a message, asking it how long it is and it will respond with the number of characters it consists of. You could use this to check if the desired password of a user exceeds the required minimum length. Notice how we add a comment to show the expected result.
Concatenatestring +string2

'a' +'b'+'c' # => 'abc'

Concatenates two or more strings together and returns the result.
Substitutegsub stands for 'globally substitute'. It substitutes all occurrences of a_string within the string with substitute.
Access string[position] 'Hello'[1] # => 'e' Access the character at the given position in the string. Be aware that the first position is actually position 0.

Arrays

An array is an ordered collection of items which is indexed by numbers. So an array contains multiple objects that are mostly related to each other. So what could you do? You could store a collection of the names of your favorite fruits and name it fruits.

This is just a small selection of things an Array can do. For more information have a look at the ruby-doc for Array.

ConceptUsageExamplesDescription
Create[contents]

[]

['Rails', 'fun', 5]

Creates an Array, empty or with the specified contents.
Number of elementsarray.size

[].size # => 0

[1, 2, 3].size # => 3

['foo', 'bar'].size # => 2

Returns the number of elements in an Array.
Access array[position]As an Array is a collection of different elements, you often want to access a single element of the Array. Arrays are indexed by numbers so you can use a number to access an individual element. Be aware that the numbering actually starts with '0' so the first element actually is the 0th. And the last element of a three element array is element number 2.
Adding an elementarray <<element Adds the element to the end of the array, increasing the size of the array by one.
Assigningarray[number] = valueAssigning new Array Values works a lot like accessing them; use an equals sign to set a new value. Voila! You changed an element of the array! Weehuuuuu!
Delete at index array.delete_at(i) Deletes the element of the array at the specified index. Remember that indexing starts at 0. If you specify an index larger than the number of elements in the array, nothing will happen.
Iteratingarray.eachdo e . end

persons.eachdo p puts p.name end

numbers.eachdo n n = n * 2 end

'Iterating' means doing something for each element of the array. Code placed between do and end determines what is done to each element in the array.

The first example prints the name of every person in the array to the console. The second example simply doubles every number of a given array.

Hashes

Hashes associate a key to some value. You may then retrieve the value based upon its key. This construct is called a dictionary in other languages, which is appropriate because you use the key to 'look up' a value, as you would look up a definition for a word in a dictionary. Each key must be unique for a given hash but values can be repeated.

Hashes can map from anything to anything! You can map from Strings to Numbers, Strings to Strings, Numbers to Booleans.. and you can mix all of those! Although it is common that at least all the keys are of the same class. Symbols are especially common as keys. Symbols look like this: :symbol. A symbol is a colon followed by some characters. You can think of them as special strings that stand for (symbolize) something! We often use symbols because Ruby runs faster when we use symbols instead of strings.

Learn more about hashes at ruby-doc.

ConceptUsageExamplesDescription
Creating{key => value}

{:hobby => 'programming'}

You create a hash by surrounding the key-value pairs with curly braces. The arrow always goes from the key to the value depicting the meaning: 'This key points to this value.'. Key-value pairs are then separated by commas.
Accessinghash[key] Accessing an entry in a hash looks a lot like accessing it in an array. However with a hash the key can be anything, not just numbers. If you try to access a key that does not exist, the value nil is returned, which is Ruby's way of saying 'nothing', because if it doesn't recognize the key it can't return a value for it.
Assigninghash[key] = value Assigning values to a hash is similar to assigning values to an array. With a hash, the key can be a number or it can be a symbol, string, number.. or anything, really!
Deletinghash.delete(key) You can delete a specified key from the hash, so that the key and its value can not be accessed.

This is an introduction to the basics of Rails. We look at the general structure of a Rails application and the important commands used in the terminal.

If you do not have Rails installed yet, there is a well maintained guide by Daniel Kehoe on how to install Rails on different platforms.

The Structure of a Rails app

Here is an overview of all the folders of a new Rails application, outliningthe purpose of each folder, and describing the most important files.
NameDescription
appThis folder contains your application. Therefore it is the most important folder in Ruby on Rails and it is worth digging into its subfolders. See the following rows.
app/assetsAssets basically are your front-end stuff. This folder contains images you use on your website, javascripts for all your fancy front-end interaction and stylesheets for all your CSS making your website absolutely beautiful.
app/controllersThe controllers subdirectory contains the controllers, which handle the requests from the users. It is often responsible for a single resource type, such as places, users or attendees. Controllers also tie together the models and the views.
app/helpersHelpers are used to take care of logic that is needed in the views in order to keep the views clean of logic and reuse that logic in multiple views.
app/mailersFunctionality to send emails goes here.
app/modelsThe models subdirectory holds the classes that model the business logic of our application. It is concerned with the things our application is about. Often this is data, that is also saved in the database. Examples here are a Person, or a Place class with all their typical behaviour.
app/views

The views subdirectory contains the display templates that will be displayed to the user after a successful request. By default they are written in HTML with embedded ruby (.html.erb). The embedded ruby is used to insert data from the application. It is then converted to HTML and sent to the browser of the user. It has subdirectories for every resource of our application, e.g. places, persons. These subdirectories contain the associated view files.

Files starting with an underscore (_) are called partials. Those are parts of a view which are reused in other views. A common example is _form.html.erb which contains the basic form for a given resource. It is used in the new and in the edit view since creating something and editing something looks pretty similar.

configThis directory contains the configuration files that your application will need, including your database configuration (in database.yml) and the particularly important routes.rb which decides how web requests are handled. The routes.rb file matches a given URL with the controller which will handle the request.
dbContains a lot of database related files. Most importantly the migrations subdirectory, containing all your database migration files. Migrations set up your database structure, including the attributes of your models. With migrations you can add new attributes to existing models or create new models. So you could add the favorite_color attribute to your Person model so everyone can specify their favorite color.
docContains the documentation you create for your application. Not too important when starting out.
libShort for library. Contains code you've developed that is used in your application and may be used elsewhere. For example, this might be code used to get specific information from Facebook.
logSee all the funny stuff that is written in the console where you started the Rails server? It is written to your development.log. Logs contain runtime information of your application. If an error happens, it will be recorded here.
publicContains static files that do not contain Ruby code, such as error pages.
scriptBy default contains what is executed when you type in the rails command. Seldom of importance to beginners.
testContains the tests for your application. With tests you make sure that your application actually does what you think it does. This directory might also be called spec, if you are using the RSpec gem (an alternative testing framework).
vendorA folder for software code provided by others ('libraries'). Most often, libraries are provided as ruby gems and installed using the Gemfile. If code is not available as a ruby gem then you should put it here. This might be the case for jQuery plugins. Probably won't be used that often in the beginning.
Gemfile

A file that specifies a list of gems that are required to run your application. Rails itself is a gem you will find listed in the Gemfile. Ruby gems are self-contained packages of code, more generally called libraries, that add functionality or features to your application.

If you want to add a new gem to your application, add 'gemgem_name' to your Gemfile, optionally specifying a version number. Save the file and then run bundle install to install the gem.

Gemfile.lockThis file specifies the exact versions of all gems you use. Because some gems depend on other gems, Ruby will install all you need automatically. The file also contains specific version numbers. It can be used to make sure that everyone within a team is working with the same versions of gems. The file is auto-generated. Do not edit this file.

Important Rails commands

Here is a summary of important commands that can be used as you develop your Ruby on Rails app. You must be in the root directory of your project to run any of these commands (with the exception of the rails new command). The project or application root directory is the folder containing all the subfolders described above (app, config, etc.).

ConceptUsageDescription
Create a new apprails newnameCreate a new Ruby on Rails application with the given name here. This will give you the basic structure to immediately get started. After this command has successfully run your application is in a folder with the same name you gave the application. You have to cd into that folder.
Start the serverrails server

You have to start the server in order for your application to respond to your requests. Starting the server might take some time. When it is done, you can access your application under localhost:3000 in the browser of your choice.

In order to stop the server, go to the console where it is running and press Ctrl + C

Scaffoldingrails generate scaffoldname attribute:type

The scaffold command magically generates all the common things needed for a new resource for you! This includes controllers, models and views. It also creates the following basic actions: create a new resource, edit a resource, show a resource, and delete a resource.

That's all the basics you need. Take this example:

rails generate scaffoldproduct name:string price:integer

Now you can create new products, edit them, view them and delete them if you don't need them anymore. Nothing stops you from creating a full fledged web shop now ;-)

Run migrationsrake db:migrateWhen you add a new migration, for example by creating a new scaffold, the migration has to be applied to your database. The command is used to update your database.
Install dependenciesbundle installIf you just added a new gem to your Gemfile you should run bundle install to install it. Don't forget to restart your server afterwards!
Check dependenciesbundle checkChecks if the dependencies listed in Gemfile are satisfied by currently installed gems
Show existing routesrake routesShows complete list of available routes in your application.

ERB: Embedded Ruby

In your views (that is, under app/views in your Rails app) you will find .html.erb files. ERB stands for Embedded RuBy. This just means that Rails processes some special tags in those files and produces HTML output to send back to the user.

There are two ERB tags that you need to remember: <%= ruby_code %> and <% ruby_code %>. Notice that the difference is the = in the first tag.

TagExamplesDescription
<%= %><%= @product.price %> It runs the Ruby code and inserts the result to the HTML at that position. You can put any kind of Ruby code between <%= and %>, for instance, <%= 9 * 3 %> will translate to 27 in the page that the user is viewing. However, typically this tag is used to display some data from a model, such as the price of a product, as shown in the example here.
<% %> The Ruby code between the delimiters <% and %> is run but the result will not be inserted at this point in the HTML. Therefore these tags are most commonly used for control flow structures such as an if statement in the example, or loops.

When you write code you will be using a text editor. Of course each text editor is different and configurable. Here are just some functions and their most general short cuts. All of them work in Sublime Text 2. Your editor may differ!

The shortcuts listed here are for Linux/Windows. On a Mac you will have to replace Ctrl with Cmd.

FunctionShortcutDescription
Save fileCtrl + S Saves the currently open file. If it was a new file you may also be asked where to save it.
UndoCtrl + Z Undo the last change you made to the current file. Can be applied multiple times in succession to undo multiple changes.
Redo

Ctrl + Y

or Ctrl + Shift + Z

Redo what you just undid with undo, can also be done multiple times.
Find in FileCtrl + F Search for a character sequence within the currently open file. Hit Enter to progress to the next match.
Find in all FilesCtrl + Shift + FSearch for a character sequence in all files of the project.
Replace

Ctrl + H

or Ctrl + R

Replace occurrences of the supplied character sequence with the other supplied character sequence. Useful when renaming something.
CopyCtrl + C Copy the currently highlighted text into the clipboard.
CutCtrl + XCopy the highlighted text into the clipboard but delete it.
PasteCtrl + V Insert whatever currently is in the clipboard (through Copy or Cut) at the current caret position. Can insert multiple times.
New FileCtrl + NCreate a new empty file.
Search and open fileCtrl + P Search for a file giving part of its name (fuzzy search). Pressing enter will open the selected file.
CommentCtrl + / Marks the selected text as a comment, which means that it will be ignored. Useful when you want to see how something behaves or looks without a specific section of code being run.

Things go wrong all the time. Don't worry, this happens to everyone. So keep calm. When you encounter an error, just google the error message. For best results, add the keywords 'rails' or 'ruby'. Results from stackoverflow.com are often really helpful. Look for those! The most experienced developers do this frequently ;-).

Here are common mistakes with a little checklist:

  • Have you run rake db:migrate to apply the newest database migrations?
  • Have you really saved the file you just changed? Unsaved files are often marked in the editor via an asterisk or a point next to their name.
  • If you just added a gem to the Gemfile, have you run bundle install to install it?
  • If you just installed a gem, have you restarted the server?

Do you need more beginner friendly in depth information about Ruby on Rails? We have started to gather free tutorials and learning material on a resources page! Please give feedback about your favorite tutorials and lessons!

Rails Migrations were introduced to be a convenient way to alter the database in a structured and organized manner, and effectively bring great consistency over time on a project.

As Ruby on Rails developers (I’m assuming you are too 😘), we should be pretty familiar with Rails Migrations and the Rails generator. But while the most common migrations are no-brainers, some of them are not -or not clearly- covered in the manual. At work at Forest Admin it’s our job to handle every possible DB schema, in Rails, NodeJS and others, which means we’ve come across a few variations already. So let’s walk through 9 tricks for generators and migrations gathered from experience (and Stack Overflow 🙊).

List of tips (Level of expertise):

  • Drop DB columns ★☆☆
  • Drop a table ★☆☆
  • Roll back a specific migration ★☆☆
  • Default values ★★☆
  • :text V/S :string ★★☆
  • Rename a column ★★☆
  • Rename a model ★★☆
  • Reset your database ★★★
  • Replicate records safely ★★★
  • Retro-update existing records’ when adding a new column ★★★
  • Migrate safely JSON stores ★★★

I’m starting with a basic that’s actually in the docs before getting to the tougher ones:

1- One line migration to drop DB columns:

Rails automatically generates this kind of migrations thanks to the command line generator:

The migration file generated will contain the following line:

For instance:

Gives:

Which would remove the field/column 'name' from the Merchant table after running rake db:migrate.
🌲 When using Forest Admin, for every new migration the server should be restarted and the webpage refreshed (🍎+R) for the new schema to be displayed correctly.

2- The right way to write a migration to drop a DB table

The Rails magic isn’t always enough: since this brutally throws away quite a lot of data at a time, there is no one line generator to drop entire tables. We need to generate a migration (important to get the timestamp that keeps everyone’s database synced), and manually add the deletion inside.

This will generate the empty .rb file in /db/migrate/ that still needs to be filled to drop the “Merchant” table in this case.

A Quick-and-Dirty™ implementation would look like this:

It’s “correct” as it shows that the migration is one-way only and should not/cannot be reversed. But in order to make a truly clean job in case these modifications were to be reversed we need to have a symmetrical migration (assuming we could recover the lost data), which we can do by declaring all the fields of our table in the migration file:

This can be long if the model is complex, but it ensures full reversibility.

Here again, changes will enter effect as usual after running rake db:migrate.

3- Rollback a specific migration

It’s generally not a good idea to do that as migrations are made to ensure consistency over projects, environments, and time, and reverting one migration breaks the chain. However in some cases and for debugging, we can rollback the migration with the corresponding timestamp with this command:

Which will revert the corresponding migration file: dbmigrate20170815201547_create_merchants.rb (where “create_merchants” does not play a role, as the only identifier is the timestamp).

Once again: ⚠️ This migrates down onlythis specific file, and not up to this specific file.

A better idea is to revert all migrations up to a certain point in time. In this case we can use the same command with the “STEP” argument defining the number of migration files we want to chronologically roll back:

As you probably know, to rollback only the last migration we can simply ommit the STEP argument:

4- Set default values for new records

Edit: as reported by MCAU, as of Rails 5.2 (and maybe some earlier versions), this is not actual anymore. Default values set in the active record migrations will apply not only to the database columns, but also when instantiating with Model.new(). The hereunder recommendation can still apply in the case you would want to have some computed “virtual” attributes being setup upon instantiation.

Defining default values in ActiveRecord only works part of the time, in particular it won’t work when calling Model.new(), as it won’t call anything from ActiveRecord.

Instead of “enforcing” the default values with a migration, writing an after_initialize callback in our model will let us set the default values we need, and even associations:

This allows to have one flexible and easily editable place to initialize our models.

Overriding initialize can also work, but let’s not forget to call super to avoid breaking the init chain.

5- When should we use ‘text’ or ‘string’ in Rails?

What’s the difference between stringand text? And when should each one be used? Quite simply, the difference relies in how the symbol is converted into its respective column type in query language: for instance with MySQL :string is mapped to VARCHAR(255).

When should each be used?

As a general rule of thumb, use :string for short text input (username, email, password, titles, etc.) and use :text for longer expected input such as descriptions, comment content, etc. However, performance requirements can come into play.

With MySQL, we can have indexes on varchars, but we can’t have any on text. ➡️ Use :string when indexes are needed.

With POSTGRES, we should use :text wherever we can, unless there is a size constraint, since there is no performance penalty for text V/S varchar.

6- Rename a database column with a one line Ruby on Rails migration

While creating a Migration as for renaming a column, Rails 4 generates a change method instead of up and down as mentioned in the above answer. The generated change method is as below :

which will create a migration file similar to this :

7- Rename an entire ActiveRecord model with a Rails migration

It’s not always easy to find the right name for each model in advance. When I choose a poor name for a model, I sometimes resolve to changing it for the greater good, despite the work involved. Here is how to proceed;

Rails doesn’t quite have a ready to fire command line for that, but we can write it ourselves quickly. Let’s create a migration:

Which we can then fill in with “rename_table”:

We will still have to go through and manually rename the model in all our files (And not forget to check for capitalized and pluralized versions of the model).

8- Purge, recreate, drop a Ruby on Rails database

To fully delete and rebuild our database, we can either:

Which will reset the database and reload the current schema, or:

Which will destroy the DB, create a new one and then migrate the current schema.

⚠️ All data will be lost in both cases.

Just to compare the different dropping and migrating commands:

  • rake db:schema:load - Creates tables and columns within the (existing) database following schema.rb. db:schema:load is used when you setup a new instance of your app.
  • rake db:reset Clears the database (presumably does a rake db:drop + rake db:create + rake db:migrate) and runs migration on a fresh database.
  • rake db:migrate runs (single) migrations that have not run yet. Typically, you would use db:migrate after having made changes to the schema of an existing DB via new migration files.
  • rake db:create creates the database
  • rake db:drop deletes the database
  • rake db:setup does db:create, db:schema:load, db:seed
  • rake db:reset does db:drop, db:setup
  • rake db:seed runs the seeds task to populate the database with preliminary data

Extra tip: Replicate/Duplicate an ActiveRecord record

Sometimes you need to make a perfect copy of a record, changing only one or a few values, such as for an association.

⛔️ Using the clone method will result in a shallow copy of the record, including copying the frozen state and the ID. No callbacks will be called either, which is probably not the effect we’ll be expecting for practical purposes.

✅ The dup method will duplicate the record calling after initialize hooks, clearing associations and IDs. A duped record will return true for new_record? and be 'saveable':

Extra Tip 2: Updating existing records with a newly added default value

(Asked in the comments)

Example: If you have a User Model and you Add a status field

How would existing User record be updated with a value of status after the migration?

(Response)

First, if you need all your users to have a status value, you would better specify a default value for new users to ensure it is not nil. This can be added as a parameter in the migration that adds the column, or later in another migration, as such:

Rails G Model Reference

Or with the one-liner:

To update the existing records, it’s a best practice to do it too through a migration, so that all the versions of the database will be up to date automatically (as opposed to running some code manually on each one of them).

The right way to do that is to create a one-way new migration where you will write the update code:

The migration should be one-way and not blindly set values back to nil in the down direction to avoid losing data if you were to roll it back.

Depending on your project, you could merge both migrations into one.

⚠️⚠️ Remember to only use raw Ruby+Rails logic in your migrations and never use anything except attributes coming from your own models.

If you need to use any kind of more advanced logic in your migration, define the methods you need in your migration and call them from there.

Using methods coming directly from your models can seem like a good idea at first to DRY your code, but with time and commits your model will change. The method you are calling in this migration might not run the same way, or exist anymore, which will prevent any new-comer to your project to run the migration set of the project smoothly.

Extra Tip 3: Migrating with Rails’ JSON Store

Working with Rails’ JSON store is remarkably easy and convenient, but requires great care to make migration reversible to prevent frustration.

Rails Commands Cheatsheet

Consider the following case, where the chronology is important:

  • We successfully create an hstore (as :text) in the DB, and migrated.
  • We then add in the model the rails line allowing this hstore to store “JSON attributes” i.e.: store :hstore_column_name, accessors: [ :attribute_one_name, ..]
  • For some reason, we decide to revert the migration to change something.
  • We make our modifications in the migration, and try to re-run migrate.

Our migration will then fail with an unintuitive error message:

What is happening is that the line declaring the hstore is still present in our model at this point. When Rails tries to run the migration, the model is called, and this line throws an error, as this same DB column we’re trying to create is supposed to be already available for use by the hstore; but does not exist yet.

Quick Fix
A quick fix is to remove the hstore declaration in the model and to migrate, then re-add it.

Better solution
In general, making hstore migrations fully reversible is not obvious. A migration allowing for model evolutions (if this hstore disappears a year from now and a newcomer needs to migrate their DB to the latest), and for data population at the same time (for instance if you are renaming an hstore or some of its attributes) will require 3 successive migration files, where hstore declarations should happen inside the migration files.

What's next?

  • Download the 'Rails migrations cheatsheet'(PDF, Free, no-email requested)
  • If you want to build your Rails Admin Panel with Forest Admin: visit our website.
  • If you want more details on the way our customers use Forest Admin, don't hesitate to contact us.
Rails



Rails G Migration