Creating a Ruby on Rails Application
This example assumes Ruby and Ruby on Rails has already been installed properly.
In a command line or terminal, you must type:
$ rails new my_app
After the application was created, switch to its folder:
$ cd my_app
Now you need to create a database from your database.yml file
rake db:create
afterwards we need the tables inside of our newly created database
rake db:migrate
Finally to start your application, run:
$ rails server
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 that still throws an error then you should check your config/database.yml
.
Create a new Rails app with Rspec
Open a command line or terminal, type:
$ rails new my_app -T
After the application was created, switch to its folder:
$ cd my_app
By default, Rails uses Test::Unit for testing. The -T switch turns off the built-in Rails test suite.
Add the rspec gem and capybara gem to your Gemfile
group :test do
gem 'rspec-rails'
gem 'capybara'
end
Rspec for unit test and capybara for the feature tests. Then run
$ bundle
Once installed we want to run this command
$ bin/rails generate rspec:install
This creates a spec folder, your spec helpers and a .rspec file
Then in your rails_helper.rb
add the following below the other requires require 'capybara/rails'
Then you are already to get testing with Rspec and Capybara
Generating A Controller
To generate a controller, go to your project directory from a command line or terminal, and run
$ rails generate controller Posts
If you open up the newly generated app/controllers/posts_controller.rb you'll see a fairly empty controller:
class PostsController < ApplicationController
# empty
end
A controller is simply a class that is defined to inherit from ApplicationController. It's inside this class that you'll define methods that will become the actions for this controller.
Create a new Rails app with a non-standard database adapter
Rails is shipped by default with ActiveRecord
, an ORM (Object Relational Mapping) derived from the pattern with the same name.
As an ORM, it is built to handle relational-mapping, and more precisely by handling SQL requests for you, hence the limitation to SQL databases only.
However, you can still create a Rails app with another database management system:
- simply create your app without active-record
$ rails app new MyApp --skip-active-record
- add your own database management system in
Gemfile
gem 'mongoid', '~> 5.0'
bundle install
and follow the installation steps from the desired database.
In this example, mongoid
is an object mapping for MongoDB
and - as many other database gems built for rails - it also inherits from ActiveModel
the same way as ActiveRecord
, which provides a common interface for many features such as validations, callbacks, translations, etc.
Other database adapters include, but are not limited to :
-
datamapper
-
sequel-rails
Creating Rails APIs in JSON
This example assumes that you have experience in creating Rails applications.
To create an API-only app in Rails 5, run
rails new name-of-app --api
Set the ActiveModelSerializer
adapter to use :json_api
# config/initializers/active_model_serializer.rb
ActiveModelSerializers.config.adapter = :json_api
Mime::Type.register "application/json", :json, %w( text/x-json application/jsonrequest application/vnd.api+json )
Generate a new scaffold for your resource
rails generate scaffold Task name:string description:text
Creating your first Rails app
Prerequisites for installing Rails 5:
- requires Ruby 2.2.2 or newer
- rvm or rbnev method can be used to install ruby
- install node js
- mysql/PostgreSQL or database of your choice should be installed
Step 1: Creating the rails app:
This command creates the basic app structure with all the required files for starting up your rails app.
rails new <name_of_app> -d mysql
-d
option is used to specify the database type. If skipped, sqlite will be used by default.
Step 2: Configuring the database
Change the database name if you like and enter the password for your development and test environment.
You should never keep your production environment passwords inside your app rather define them in the environment and use it in your app as shown below.
# /app/config/database.yml
default: &default
adapter: mysql2
encoding: utf8
pool: 5
username: root
password: mysecretpassword
socket: /tmp/mysql.sock
development:
<<: *default
database: development
# Warning: The database defined as "test" will be erased and
# re-generated from your development database when you run "rake".
# Do not set this db to the same as development or production.
test:
<<: *default
database: test
production:
<<: *default
database: production
username: ROOT
password: <%= ENV['DATABASE_PASSWORD'] %>
Step 3: Installing the gems
Run bundle install
to install all the gems that are there in the Gemfile.
Whenever you update the Gemfile by adding a new gem, bundle install
should be run again.
Step 4: Creating the database
Run the following command to create the database:
# works only in rails 5
rails db:create
# works in all versions of rails
rake db:create
Step 5: Using Scaffold
Use the scaffold
command to generate the model, view and controller if you are new to Rails as it gives greater insights on how the MVC is created neatly in the app.
rails generate scaffold User name:string email:string biodata:text
The command generates:
- Model named
user.rb
- Controller named
users_controller.rb
- Views such as
index.html.erb
,show.html.erb
,edit.html.erb
Instead of generate
, the short form g
can also be used:
rails g scaffold User name:string email:string biodata:text
To roll back, simply use the following command:
rails destroy scaffold User name:string email:string biodata:text
Instead of destroy
, the short form d
can also be used:
rails d scaffold User name:string email:string biodata:text
Step 6: Routing
As we have used the scaffold option for generating the MVC, it automatically adds the following line in the routes.rb
file:
resources :users
Step 7: Running the migrations
In order to create the tables in the database we should use the following command:
# only works in rails 5
rails db:migrate
# works in all rails versions
rake db:migrate
# for running a particular migration
rails db:migrate:up VERSION=20160723032919
# for undoing a particular migration
rails db:migrate:down VERSION=20160723032919
Step 8: Running the app
Once the above setup is done your app is just one step away from starting. Use the following command to start it:
# starts the app on port 3000
rails server
# or
rails s
# or if port 3000 is already in use then use -p option to specify a different port
rails s -p 3001
Step 9: Verifying in browser
Enter localhost:3000
in your browser and you should see:
Yay! you are on Rails
This means your app is up and running successfully. You can also open the user's index
page, which we created few minutes back by entering localhost:3000/users
in your browser.
Generate a Resource with Scaffolds
From guides.rubyonrails.org: "Instead of generating a model directly . . . 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."
Here's an example of scaffolding a resource called "Task" with a string and a text description:
rails generate scaffold Task name:string description:text
Installing Rails On Ubuntu
On a clean ubuntu, installation of Rails should be straight forward
Upgrading ubuntu packages
sudo apt-get update
sudo apt-get upgrade
Install Ruby and Rails dependecies
sudo apt-get install git-core curl zlib1g-dev build-essential libssl-dev libreadline-dev libyaml-dev libsqlite3-dev sqlite3 libxml2-dev libxslt1-dev libcurl4-openssl-dev python-software-properties libffi-dev
Installing ruby version manager. In this case the easy one is using rbenv
git clone https://github.com/rbenv/rbenv.git ~/.rbenv
echo 'export PATH="$HOME/.rbenv/bin:$PATH"' >> ~/.bashrc
echo 'eval "$(rbenv init -)"' >> ~/.bashrc
Installing Ruby Build
git clone https://github.com/rbenv/ruby-build.git ~/.rbenv/plugins/ruby-build
echo 'export PATH="$HOME/.rbenv/plugins/ruby-build/bin:$PATH"' >> ~/.bashrc
Restart Shell
exec $SHELL
Install ruby
rbenv install 2.3.1
rbenv global 2.3.1
rbenv rehash
Installing rails
gem install rails