Creating a Ruby on Rails Application
suggest changeThis example assumes Ruby and Ruby on Rails have already been installed properly. If not, you can find how to do it here.
Open up a command line or terminal. To generate a new rails application, use rails new command followed by the name of your application:
$ rails new my_app
If you want to create your Rails application with a specific Rails version then you can specify it at the time of generating the application. To do that, use rails _version_ new followed by the application name:
$ rails _4.2.0_ new my_app
This creates a Rails application whose module is MyApp, in a my_app directory, and installs the Gemfile dependencies with bundle install.
To switch to your newly created app’s directory, use the cd command, which stands for change directory.
$ cd my_app
The my_app directory has a number of auto-generated files and folders that make up the structure of a Rails application. Following is a list of files and folders that are created by default:
| File or folder | Purpose |
|---|---|
app/ |
Controllers, models, views, helpers, mailers, and assets. |
bin/ |
The rails script and other scripts used to set up, update, deploy, or run the app. |
config/ |
Routes, database configuration, and other settings. |
config.ru |
Rack configuration used to start the application. |
db/ |
The schema and migrations. |
Gemfile, Gemfile.lock |
Gem dependencies, installed by Bundler. |
lib/ |
Extra modules for the application. |
log/ |
Application log files. |
public/ |
Files served as-is, including static files and compiled assets. |
Rakefile |
Loads tasks that can be run from the command line. |
README.md |
Short instructions for the application. |
test/ |
Tests, fixtures, and other test files. |
tmp/ |
Temporary files, such as cache and pid files. |
vendor/ |
Third-party code, including vendored gems. |
Now you need to create a database from your database.yml file:
rake db:create
# or, on Rails 5 and later:
rails db:create
Run migrations to create the tables:
rake db:migrate
# or, on Rails 5 and later:
rails db:migrate
To start the application, we need to fire up the server:
$ rails server
# OR
$ rails s
By default, Rails serves the application on port 3000. Use another port like this:
$ rails s -p 3010
If you navigate to http://localhost:3000 in your browser, you will see a Rails welcome page, showing that your application is now running.
If it throws an error, there may be several possible problems:
- There is a problem with the
config/database.yml - You have dependencies in your
Gemfilethat have not been installed. - You have pending migrations. Run
rails db:migrate - To undo the latest migration, run
rails db:rollback.
If that still throws an error, then you should check your config/database.yml