Rails console shortcuts, tips, and tricks
Rails new application-name
A well-known command in rails used to create new rails application.
Examples:
- rails new -d postgreSQL — This will make Postgres as your application database
- rails new –skip-test — This will skip your test files creation
- rails new –api — For only API applications
- rails new –skip-javascript — This will skip your JavaScript files
Rails server
By default rails come with one web server, this web server may vary depends upon the rails versions, Currently, the latest rails version uses puma.
Examples:
rails s -e production -p 3001
rails s -e development -p 3002
Rails generate
This command will help you to create assets, controllers, models, migrations, helpers, jobs, mailers, test files, scaffold, tasks.
Clearing theConsole
To get a clean slate in your console, use Command + K
on the Mac.
Reloading theConsole
reload! a command to pick up the latest version of your code:
>> reload! Reloading… => true
Autocompleting
console
has autocompletion support.
Suppose you have a Article
model that you previously used in the console
and now you want to use it to run a query. Start by typing Art
and then hit Tab
:
>> Art<Tab>>>> Article.w<Tab>
Now hit Tab
a second time and you’ll get a list of valid completions:
>> Article.w<Tab><Tab> Article.where , Article.with_scope, Article.with_exclusive_scope Article.with_warnings, Article.with_options
Trying Out ViewHelpers
>> helper.pluralize(702, ‘7th floor, mangalam fun square’) => “702 7th floor, mangalam fun squares” >> helper.number_to_currency(10.50) => “$10.50” >> helper.truncate(“Pradeep Chauhan”, length: 12) => “Pradeep C…”>> helper.title_tag(User.first) => “<title>Pradeep Chauhan</title>”
Trying Out RouteHelpers
>> app.articles_path => “/articles” >> app.article_path(Article.first) => “/articles/1”
Use the helper
and the app
objects together, and you can generate links in the console:
>> helper.link_to(“Articles”, app.articles_path) => “<a href=”/articles”>Articles</a>”
Issuing Requests Interactively
The best part is that no browser or server is required.
>> app.get “/articles” => 200 >> app.get “/articles/178” => 302>> app.post “/session”, email: ‘[email protected]’, password: ‘****’ => 302
Playing in theSandbox
Sometimes we need to experiment with data in the console without the fear of permanently changing data
$ rails console — sandbox Loading development environment in sandbox Any modifications you make will be rolled back on exit >>
>> User.destroy(1) >> User.find(1) ActiveRecord::RecordNotFound: Could not find User with id=1 >> exit (12.3ms) ROLLBACK
The user was successfully deleted, but notice that the database transaction got rolled back after the exit
Rails stat
This command will help you to find out the statistics of your application code. It will display the number of classes, number of lines, number of methods your controllers, models, helpers, workers, mailers using.