Ruby On Rails Cheat Sheet



  1. Ruby On Rails Cheat Sheet Answers
  2. Ruby On Rails Cheat Sheet
  3. Ruby Cheat Sheet Pdf
  4. Ruby On Rails Cheat Sheet Download

This tutorial assumes you have basic Rails knowledge from reading the Getting Started with Rails Guide.

1 Command Line Basics

There are a few commands that are absolutely critical to your everyday usage of Rails. In the order of how much you'll probably use them are:

  1. Ruby on Rails Cheat Sheet A quick reference guide for Ruby on Rails, containing the default directory structure, predefined variables, methods, reserved words and regular expression syntax. Jonathan Irvin Getting Technical.
  2. Cheat Sheet Conventions. 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.
  3. Tagged with ruby, rails, beginners. My beloved Ruby on Rails cheat sheet # ruby # rails # beginners. Eric Chapman Feb 8 ・Updated on.

Programming isn't easy, especially if you're not good at memorization. Depending on the language you are working with, you must recall a fair share of syntax, commands, and functions. Even if you work with code every day, it's information that's easy to forget. That's exactly what our cheat sheets are for. The Ruby cheat sheets we provide contain common syntaxes and data properties. Ruby on Rails Cheat Sheet.png, pdf Ruby on Rails Cheat Sheet backup RubyOnRails-Cheatsheet.pdf RubyOnRails-Cheatsheet backup Ruby on Rails cheat sheet guide.pdf Ruby on Rails cheat sheet guide backup What Goes Where a Ruby on Rails cheat sheet.pdf What Goes Where a Ruby on Rails cheat sheet backup Flexible Rails: Flex 3 on.

  • bin/rails console
  • bin/rails server
  • bin/rails test
  • bin/rails generate
  • bin/rails db:migrate
  • bin/rails db:create
  • bin/rails routes
  • bin/rails dbconsole
  • rails new app_name

You can get a list of rails commands available to you, which will often depend on your current directory, by typing rails --help. Each command has a description, and should help you find the thing you need.

Let's create a simple Rails application to step through each of these commands in context.

1.1 rails new

The first thing we'll want to do is create a new Rails application by running the rails new command after installing Rails.

You can install the rails gem by typing gem install rails, if you don't have it already.

Rails will set you up with what seems like a huge amount of stuff for such a tiny command! You've got the entire Rails directory structure now with all the code you need to run our simple application right out of the box.

If you wish to skip some files or components from being generated, you can append the following arguments to your rails new command:

ArgumentDescription
--skip-gemfileDon't create a Gemfile
--skip-gitSkip .gitignore file
--skip-keepsSkip source control .keep files
--skip-action-mailerSkip Action Mailer files
--skip-action-textSkip Action Text gem
--skip-active-recordSkip Active Record files
--skip-active-storageSkip Active Storage files
--skip-pumaSkip Puma related files
--skip-action-cableSkip Action Cable files
--skip-sprocketsSkip Sprockets files
--skip-springDon't install Spring application preloader
--skip-listenDon't generate configuration that depends on the listen gem
--skip-javascriptSkip JavaScript files
--skip-turbolinksSkip turbolinks gem
--skip-testSkip test files
--skip-system-testSkip system test files
--skip-bootsnapSkip bootsnap gem

1.2 bin/rails server

Ruby On Rails Cheat Sheet Answers

The bin/rails server command launches a web server named Puma which comes bundled with Rails. You'll use this any time you want to access your application through a web browser.

With no further work, bin/rails server will run our new shiny Rails app:

With just three commands we whipped up a Rails server listening on port 3000. Go to your browser and open http://localhost:3000, you will see a basic Rails app running.

You can also use the alias 's' to start the server: bin/rails s.

The server can be run on a different port using the -p option. The default development environment can be changed using -e.

The -b option binds Rails to the specified IP, by default it is localhost. You can run a server as a daemon by passing a -d option.

1.3 bin/rails generate

The bin/rails generate command uses templates to create a whole lot of things. Running bin/rails generate by itself gives a list of available generators:

You can also use the alias 'g' to invoke the generator command: bin/rails g.

You can install more generators through generator gems, portions of plugins you'll undoubtedly install, and you can even create your own!

Using generators will save you a large amount of time by writing boilerplate code, code that is necessary for the app to work.

Let's make our own controller with the controller generator. But what command should we use? Let's ask the generator:

All Rails console utilities have help text. As with most *nix utilities, you can try adding --help or -h to the end, for example bin/rails server --help.

The controller generator is expecting parameters in the form of generate controller ControllerName action1 action2. Let's make a Greetings controller with an action of hello, which will say something nice to us.

What all did this generate? It made sure a bunch of directories were in our application, and created a controller file, a view file, a functional test file, a helper for the view, a JavaScript file, and a stylesheet file.

Check out the controller and modify it a little (in app/controllers/greetings_controller.rb):

Then the view, to display our message (in app/views/greetings/hello.html.erb):

Fire up your server using bin/rails server.

The URL will be http://localhost:3000/greetings/hello.

With a normal, plain-old Rails application, your URLs will generally follow the pattern of http://(host)/(controller)/(action), and a URL like http://(host)/(controller) will hit the index action of that controller.

Rails comes with a generator for data models too.

For a list of available field types for the type parameter, refer to the API documentation for the add_column method for the SchemaStatements module. The index parameter generates a corresponding index for the column.

But instead of generating a model directly (which we'll be doing later), let's set up a scaffold. A scaffold in Rails is a full set of model, database migration for that model, controller to manipulate it, views to view and manipulate the data, and a test suite for each of the above.

We will set up a simple resource called 'HighScore' that will keep track of our highest score on video games we play.

The generator checks that there exist the directories for models, controllers, helpers, layouts, functional and unit tests, stylesheets, creates the views, controller, model and database migration for HighScore (creating the high_scores table and fields), takes care of the route for the resource, and new tests for everything.

The migration requires that we migrate, that is, run some Ruby code (living in that 20130717151933_create_high_scores.rb) to modify the schema of our database. Which database? The SQLite3 database that Rails will create for you when we run the bin/rails db:migrate command. We'll talk more about that command below.

Let's talk about unit tests. Unit tests are code that tests and makes assertionsabout code. In unit testing, we take a little part of code, say a method of a model,and test its inputs and outputs. Unit tests are your friend. The sooner you makepeace with the fact that your quality of life will drastically increase when you unittest your code, the better. Seriously. Please visitthe testing guide for an in-depthlook at unit testing.

Let's see the interface Rails created for us.

Go to your browser and open http://localhost:3000/high_scores, now we can create new high scores (55,160 on Space Invaders!)

1.4 bin/rails console

The console command lets you interact with your Rails application from the command line. On the underside, bin/rails console uses IRB, so if you've ever used it, you'll be right at home. This is useful for testing out quick ideas with code and changing data server-side without touching the website.

You can also use the alias 'c' to invoke the console: bin/rails c.

You can specify the environment in which the console command should operate.

If you wish to test out some code without changing any data, you can do that by invoking bin/rails console --sandbox.

1.4.1 The app and helper objects

Inside the bin/rails console you have access to the app and helper instances.

With the app method you can access named route helpers, as well as do requests.

With the helper method it is possible to access Rails and your application's helpers.

1.5 bin/rails dbconsole

bin/rails dbconsole figures out which database you're using and drops you into whichever command line interface you would use with it (and figures out the command line parameters to give to it, too!). It supports MySQL (including MariaDB), PostgreSQL, and SQLite3.

You can also use the alias 'db' to invoke the dbconsole: bin/rails db.

If you are using multiple databases, bin/rails dbconsole will connect to the primary database by default. You can specify which database to connect to using --database or --db:

1.6 bin/rails runner

runner runs Ruby code in the context of Rails non-interactively. For instance:

You can also use the alias 'r' to invoke the runner: bin/rails r.

You can specify the environment in which the runner command should operate using the -e switch.

You can even execute ruby code written in a file with runner.

1.7 bin/rails destroy

Think of destroy as the opposite of generate. It'll figure out what generate did, and undo it.

RailsRuby

You can also use the alias 'd' to invoke the destroy command: bin/rails d.

1.8 bin/rails about

bin/rails about gives information about version numbers for Ruby, RubyGems, Rails, the Rails subcomponents, your application's folder, the current Rails environment name, your app's database adapter, and schema version. It is useful when you need to ask for help, check if a security patch might affect you, or when you need some stats for an existing Rails installation.

1.9 bin/rails assets:

You can precompile the assets in app/assets using bin/rails assets:precompile, and remove older compiled assets using bin/rails assets:clean. The assets:clean command allows for rolling deploys that may still be linking to an old asset while the new assets are being built.

If you want to clear public/assets completely, you can use bin/rails assets:clobber.

1.10 bin/rails db:

The most common commands of the db: rails namespace are migrate and create, and it will pay off to try out all of the migration rails commands (up, down, redo, reset). bin/rails db:version is useful when troubleshooting, telling you the current version of the database.

More information about migrations can be found in the Migrations guide.

1.11 bin/rails notes

bin/rails notes searches through your code for comments beginning with a specific keyword. You can refer to bin/rails notes --help for information about usage.

By default, it will search in app, config, db, lib, and test directories for FIXME, OPTIMIZE, and TODO annotations in files with extension .builder, .rb, .rake, .yml, .yaml, .ruby, .css, .js, and .erb.

1.11.1 Annotations

You can pass specific annotations by using the --annotations argument. By default, it will search for FIXME, OPTIMIZE, and TODO.Note that annotations are case sensitive.

1.11.2 Tags

You can add more default tags to search for by using config.annotations.register_tags. It receives a list of tags.

1.11.3 Directories

You can add more default directories to search from by using config.annotations.register_directories. It receives a list of directory names.

1.11.4 Extensions

You can add more default file extensions to search from by using config.annotations.register_extensions. It receives a list of extensions with its corresponding regex to match it up.

1.12 bin/rails routes

bin/rails routes will list all of your defined routes, which is useful for tracking down routing problems in your app, or giving you a good overview of the URLs in an app you're trying to get familiar with.

1.13 bin/rails test

A good description of unit testing in Rails is given in A Guide to Testing Rails Applications

Rails comes with a test framework called minitest. Rails owes its stability to the use of tests. The commands available in the test: namespace helps in running the different tests you will hopefully write.

1.14 bin/rails tmp:

The Rails.root/tmp directory is, like the *nix /tmp directory, the holding place for temporary files like process id files and cached actions.

Ruby

The tmp: namespaced commands will help you clear and create the Rails.root/tmp directory:

  • bin/rails tmp:cache:clear clears tmp/cache.
  • bin/rails tmp:sockets:clear clears tmp/sockets.
  • bin/rails tmp:screenshots:clear clears tmp/screenshots.
  • bin/rails tmp:clear clears all cache, sockets, and screenshot files.
  • bin/rails tmp:create creates tmp directories for cache, sockets, and pids.

1.15 Miscellaneous

  • bin/rails initializers prints out all defined initializers in the order they are invoked by Rails.
  • bin/rails middleware lists Rack middleware stack enabled for your app.
  • bin/rails stats is great for looking at statistics on your code, displaying things like KLOCs (thousands of lines of code) and your code to test ratio.
  • bin/rails secret will give you a pseudo-random key to use for your session secret.
  • bin/rails time:zones:all lists all the timezones Rails knows about.

1.16 Custom Rake Tasks

Custom rake tasks have a .rake extension and are placed inRails.root/lib/tasks. You can create these custom rake tasks with thebin/rails generate task command.

To pass arguments to your custom rake task:

Rails

Ruby On Rails Cheat Sheet

You can group tasks by placing them in namespaces:

Invocation of the tasks will look like:

If you need to interact with your application models, perform database queries, and so on, your task should depend on the environment task, which will load your application code.

2 The Rails Advanced Command Line

More advanced use of the command line is focused around finding useful (even surprising at times) options in the utilities, and fitting those to your needs and specific work flow. Listed here are some tricks up Rails' sleeve.

2.1 Rails with Databases and SCM

When creating a new Rails application, you have the option to specify what kind of database and what kind of source code management system your application is going to use. This will save you a few minutes, and certainly many keystrokes.

Let's see what a --git option and a --database=postgresql option will do for us:

We had to create the gitapp directory and initialize an empty git repository before Rails would add files it created to our repository. Let's see what it put in our database configuration:

It also generated some lines in our database.yml configuration corresponding to our choice of PostgreSQL for database.

Ruby Cheat Sheet Pdf

The only catch with using the SCM options is that you have to make your application's directory first, then initialize your SCM, then you can run the rails new command to generate the basis of your app.

Feedback

You're encouraged to help improve the quality of this guide.

Please contribute if you see any typos or factual errors. To get started, you can read our documentation contributions section.

You may also find incomplete content or stuff that is not up to date. Please do add any missing documentation for main. Make sure to check Edge Guides first to verify if the issues are already fixed or not on the main branch. Check the Ruby on Rails Guides Guidelines for style and conventions.

If for whatever reason you spot something to fix but cannot patch it yourself, please open an issue.

Ruby On Rails Cheat Sheet Download

And last but not least, any kind of discussion regarding Ruby on Rails documentation is very welcome on the rubyonrails-docs mailing list.