Getting started with Rails
- select the contributor at the end of the page -
Rails may be the most popular framework for building Web applications in Ruby, but it’s more than that—it’s a Ruby gem itself. Of course, as a gem, Rails also has gem dependencies. So it’s a good idea to first learn how to write stand-alone Ruby programs and get to know the Ruby language, along with its syntax and rules, before diving into Rails. If you skip this step, it’s likely you’ll have difficulty understanding the Rails framework which is written in Ruby, for Ruby.
If you’re new to Ruby and Ruby on Rails, you’ll want to use RVM to install Rails. RVM is a Ruby gem management system that handles the gem dependencies for you. There are other options, but not all of them manage the gem dependencies, which could end up putting you in a bind rather quickly if you’re not careful. Another popular option is rbenv, though I recommend RVM, as it’s what I use to develop shippable Rails apps professionally.
Installing Rails on Windows
The Rails Girls and Railsbridge organizations recommend the RailsInstaller. And although there is a version available for Mac OS, Mac users should first install Xcode in order to install RVM and the Postgres database (this is what most Rails applications use in production environments).
Installing Rails on Mac OS X Yosemite
First, make sure you’ve got the latest version of Xcode installed. Then, consider installing Homebrew, which can make future application installations on Macs less painful. Open your terminal to install Homebrew by running the following command on a single line in the terminal and press Return:
ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
Follow the instructions. Once Homebrew finishes installing, run this command in your terminal:
If all went well, you should get this output message:
|Your system is ready to brew|
Next, install Git and RVM using Homebrew:
brew install git
If that worked, running the command 'git –version' should result in getting a message like, 'git version 2.3.1 or later.' Next, download and install Github for Mac, and follow the instructions and prompts through the setup. This free video tutorial can help. Finally, install RVM, which will automatically install the latest versions of Ruby and Rails for you. In your terminal, run the following command:
|curl -L https://get.rvm.io | bash -s stable --auto-dotfiles --autolibs=enable --rails|
Once it’s finished, close and relaunch the terminal and run this command:
|type rvm | head -1|
If you get a message like 'rvm is a function' or something very similar, you’re good to go!
You can find plenty of information about how the RVM gem management system is installed by running the commands 'echo $PATH and rvm list.'
Your first Rails app
Now that you’ve installed RVM with the latest versions of Ruby and Rails, you now have another command line tool to use for generating everything from a fresh new Rails application to models, controllers, individual migrations, or even a scaffold. It’s the Rails scaffolding that made Rails so popular, providing the kind of instant gratification for assembling a simple but beautiful Web application in the least amount of time.
The architecture of Rails applications is a Model, Views and Controllers (MVC) architecture. The model is responsible for maintaining the app’s state, as well as serving as an enforcer of the app’s business logic. Think of the model as a gatekeeper that doubles as a data store. Meanwhile, the view generates a user interface based on the logic in the model and the interaction with that model by a controller which receives requests or input from users interacting with the Web page.
And then we have the controller which is kind of like a friendly traffic cop (think Andy Griffith of Mayberry). It coordinates interactions between the user, the templates (or views), and the model. It’s also responsible for routing external events/requests to internal actions, managing caching, helper modules (which gives a boost to view templates without overwhelming their code), and managing sessions.
The controllers in Rails automatically render views with names that correspond to valid routes. For example, if you have a products controller with an index method (controller methods are also called actions), you would have a view file named app/views/products/index.html.erb and Rails would automatically display that template in the browser when you navigate to /products in your browser’s address bar—provided you have a route for it.
The route can be the app’s root, root ‘store#index’, as: ‘store’ , which tells Rails to create a store_path accessor method. The route can also be a named route, a regular route or a resource route; resources :products, just to list a few examples. You can find more examples of these in the routes file that Rails generates. The routes file has commented-out text in it that serves as a “how-to” for writing the code for your application’s routes.
As an aside, the order in which Rails routes execute is based on the order in which they were created; first created gets highest priority. You can generate models, controllers, views and individual migrations separately as this example shows, with the generating of an individual model for a flashcards app:
Opening up your text editor, you’ll see the database migration table this has created:
If you don’t want to write the code for each controller and model individually (although you often won’t have a choice), you can run the scaffold command. This is what the authors of the “Agile Web Development with Rails 4” instruct in their tutorial for putting together a simple e-commerce app:
A model is automatically mapped to a database table whose name is the plural form of the model’s class. So, Rails will associate that model with a database table named “products.” And this is how you’ll perform SQL search queries for it as well
Although Rails comes with its own built-in SQL database for development, called SQLite3, you can actually specify a different database when you first run the rails command to make a new app by using the –d flag followed by your desired database instead of the one that comes built into Rails. For example, if you wanted to use MySQL or Postgres, you would specify that like so: rails new myOtherAwesomeApp –d postgresql
You are not tethered to SQLite3 if you do not want to use it (as long as you have other databases installed).
OK, let’s get back to the Rails scaffold example: Looking in your db/migrate folder, the corresponding migrations this scaffolding command wrote for you look like this:
Rails maps relational data onto objects in what is known as Object Relational Mapping (ORM). ORM libraries map database tables to classes, rows to objects, and columns to object attributes. In Rails, ActiveRecord is the ORM layer and serves as the foundation of the Rails MVC architecture.
Since Ruby marshals objects (meaning it can take an object and convert it to a stream of bytes that can be stored outside of the application) it should be no surprise that Rails can also marshal objects. Rails uses marshaling to store session data.
Rake is a command similar to Make that is for Rails. Rake looks for migrations not yet applied to the database and also provides information about Rails routes, and performs tests. The command rake routes will show you more information about the app’s available routes.
You can also get information about your app’s routes from the browser when you start up the Rails server, as this example from the Railsbridge curriculum shows:
Basically, Rails allows you to learn Web app development by giving you the information you need in order to make sure the communication between models and views and controllers via the Rails routes are all set up correctly. When you generate migrations, either by generating individual models or generating a scaffold, you must run your migrations by running the following command: rake db:migrate
Note: If you forget to run your migrations, your app won’t work when you start up the Rails server to view it in your localhost browser! If you’re not sure whether you ran your migrations or not, there’s a command rake db:migrate:status (shown below) that will tell you. If you did run your migrations, they’ll show as “up” under the migration status. If you have any migrations that were not run, they’ll show as “down.”
Not only can you run migrations and check their status, you can also roll back and reset your migrations if you made a mistake and forgot to include a field in your database table. Those commands are rake db:rollback and rake db:reset, respectively. Additionally, Rails has the ability to import seed data, and you can seed your app’s database by running the command rake db:seed.
Now, a word of caution here: If you’ve already entered other objects into your database and then decide to try this rake command (for seeding your database), you’ll automatically lose what was in your database because the seeds.rb script removes existing data from the tables before loading new data. So, it’s best to use this rake command for seeding your database if you did not spend hours typing your own information for your application’s database tables.
You can also use rake to run tests in Rails' built-in test suite: rake db:test, rake db:test:models, and rake db:test:controllers runs tests on the entire application, unit tests, and integration tests, respectively.
(Yes, I really did write my unit tests, and yes you really can write code that will pass those tests—and the built-in Rails test suite makes this a lot less difficult than you’d think!)
You should familiarize yourself with the rake tools that Rails offers, because it’ll make your life a lot easier as a developer.
The templates for displaying page views in Rails use embedded Ruby, and the syntax looks a lot like ASP.NET. It’s in these .erb files, in the views directory of the Rails app, where you’ll write your code for everything involving rendering views; what the end user sees on their screen. This includes everything from displaying links and images to shopping carts to implementing the Rails form_for method to generate a form for receiving user input, such as a contact form. More on this later.
Using the products controller and views, and the Product model as example mentioned earlier, this is what you’ll see if you type http://localhost: 300 in your address bar after following the tutorial in the “Agile Web Development With Rails 4” book for creating the products views:
The Rails console
The Rails console is, to put it simply, an interactive Ruby shell inside a Rails app. In other words, it’s irb for Rails. You can use the Rails console for debugging code, checking the results of test code snippets, or modifying your database through the ActiveRecord model in your Rails project.
The abbreviated command you would run for getting into the Rails console is rails c. However, be aware that anything you create while in the Rails console will change your database. There is a way you can practice some commands and queries in the Rails console without altering the records in your app’s database. Run the command rails c --sandbox instead; this allows you to go into the Rails console and interact with it without making any permanent changes to the database.
Inside the Rails console, you can run Ruby commands and use any of the methods available in a Rails application. The Rails console loads in the development environment by default, but if you pass the production parameter to the rails c command, you can run the Rails console in the production environment too.
You can instantiate class objects, such as a product object from the class Product in my example app in and create a record for it like so: p = Product.new. The Rails console also has some auto-complete features. For one, you can press the Tab key twice to bring up a list of available methods that you can call on that object that’s a Rails String class:
You can also make the output in the Rails console easier to read by calling the y method on it, which converts it to a YAML output.
And here are just a few of the methods we can call on a product object we instantiate in the Rails console:
This tells us that the instantiated p object is a new record, it does not have a nil value, and it is not html safe (we’ll cover cross-site scripting protection in a later post).
We can also use the Rails console to get instant access to a controller class, and get to see a session id by running the command app.cookies. We can call a helper method to see the html output of a text field, and we can call the pluralize method which will return a value. We can also check to see the different methods available to us, and which methods end in path.
We covered a lot, but there are so many more things you can do once you really become familiar with the Rails console.