Getting Started with Rails — Ruby on Rails Guides (2024)

1 Guide Assumptions

This guide is designed for beginners who want to get started with a Railsapplication from scratch. It does not assume that you have any prior experiencewith Rails. However, to get the most out of it, you need to have someprerequisites installed:

  • The Ruby language version 1.9.3 or newer.
  • The RubyGems packaging system, which is installed with Rubyversions 1.9 and later. To learn more about RubyGems, please read the RubyGems Guides.
  • A working installation of the SQLite3 Database.

Rails is a web application framework running on the Ruby programming language.If you have no prior experience with Ruby, you will find a very steep learningcurve diving straight into Rails. There are several curated lists of online resourcesfor learning Ruby:

Be aware that some resources, while still excellent, cover versions of Ruby as old as1.6, and commonly 1.8, and will not include some syntax that you will see in day-to-daydevelopment with Rails.

2 What is Rails?

Rails is a web application development framework written in the Ruby language.It is designed to make programming web applications easier by making assumptionsabout what every developer needs to get started. It allows you to write lesscode while accomplishing more than many other languages and frameworks.Experienced Rails developers also report that it makes web applicationdevelopment more fun.

Rails is opinionated software. It makes the assumption that there is the "best"way to do things, and it's designed to encourage that way - and in some cases todiscourage alternatives. If you learn "The Rails Way" you'll probably discover atremendous increase in productivity. If you persist in bringing old habits fromother languages to your Rails development, and trying to use patterns youlearned elsewhere, you may have a less happy experience.

The Rails philosophy includes two major guiding principles:

  • Don't Repeat Yourself: DRY is a principle of software development whichstates that "Every piece of knowledge must have a single, unambiguous, authoritativerepresentation within a system." By not writing the same information over and overagain, our code is more maintainable, more extensible, and less buggy.
  • Convention Over Configuration: Rails has opinions about the best way to do manythings in a web application, and defaults to this set of conventions, rather thanrequire that you specify every minutiae through endless configuration files.

3 Creating a New Rails Project

The best way to use this guide is to follow each step as it happens, no code orstep needed to make this example application has been left out, so you canliterally follow along step by step.

By following along with this guide, you'll create a Rails project calledblog, a (very) simple weblog. Before you can start building the application,you need to make sure that you have Rails itself installed.

The examples below use $ to represent your terminal prompt in a UNIX-like OS,though it may have been customized to appear differently. If you are using Windows,your prompt will look something like c:\source_code>

3.1 Installing Rails

Open up a command line prompt. On Mac OS X open Terminal.app, on Windows choose"Run" from your Start menu and type 'cmd.exe'. Any commands prefaced with adollar sign $ should be run in the command line. Verify that you have acurrent version of Ruby installed:

A number of tools exist to help you quickly install Ruby and Rubyon Rails on your system. Windows users can use Rails Installer,while Mac OS X users can use Tokaido.

$ ruby -vruby 2.0.0p353

If you don't have Ruby installed have a look atruby-lang.org for possible ways toinstall Ruby on your platform.

Many popular UNIX-like OSes ship with an acceptable version of SQLite3. Windowsusers and others can find installation instructions at the SQLite3 website.Verify that it is correctly installed and in your PATH:

$ sqlite3 --version

The program should report its version.

To install Rails, use the gem install command provided by RubyGems:

$ gem install rails

To verify that you have everything installed correctly, you should be able torun the following:

$ rails --version

If it says something like "Rails 4.2.1", you are ready to continue.

3.2 Creating the Blog Application

Rails comes with a number of scripts called generators that are designed to makeyour development life easier by creating everything that's necessary to startworking on a particular task. One of these is the new application generator,which will provide you with the foundation of a fresh Rails application so thatyou don't have to write it yourself.

To use this generator, open a terminal, navigate to a directory where you haverights to create files, and type:

$ rails new blog

This will create a Rails application called Blog in a blog directory andinstall the gem dependencies that are already mentioned in Gemfile usingbundle install.

You can see all of the command line options that the Rails applicationbuilder accepts by running rails new -h.

After you create the blog application, switch to its folder:

$ cd blog

The blog directory has a number of auto-generated files and folders that makeup the structure of a Rails application. Most of the work in this tutorial willhappen in the app folder, but here's a basic rundown on the function of eachof the files and folders that Rails created by default:

File/FolderPurpose
app/Contains the controllers, models, views, helpers, mailers and assets for your application. You'll focus on this folder for the remainder of this guide.
bin/Contains the rails script that starts your app and can contain other scripts you use to setup, deploy or run your application.
config/Configure your application's routes, database, and more. This is covered in more detail in Configuring Rails Applications.
config.ruRack configuration for Rack based servers used to start the application.
db/Contains your current database schema, as well as the database migrations.
Gemfile
Gemfile.lock
These files allow you to specify what gem dependencies are needed for your Rails application. These files are used by the Bundler gem. For more information about Bundler, see the Bundler website.
lib/Extended modules for your application.
log/Application log files.
public/The only folder seen by the world as-is. Contains static files and compiled assets.
RakefileThis file locates and loads tasks that can be run from the command line. The task definitions are defined throughout the components of Rails. Rather than changing Rakefile, you should add your own tasks by adding files to the lib/tasks directory of your application.
README.rdocThis is a brief instruction manual for your application. You should edit this file to tell others what your application does, how to set it up, and so on.
test/Unit tests, fixtures, and other test apparatus. These are covered in Testing Rails Applications.
tmp/Temporary files (like cache, pid, and session files).
vendor/A place for all third-party code. In a typical Rails application this includes vendored gems.

4 Hello, Rails!

To begin with, let's get some text up on screen quickly. To do this, you need toget your Rails application server running.

4.1 Starting up the Web Server

You actually have a functional Rails application already. To see it, you need tostart a web server on your development machine. You can do this by running thefollowing in the blog directory:

$ bin/rails server

If you are using Windows, you have to pass the scripts under the binfolder directly to the Ruby interpreter e.g. ruby bin\rails server.

Compiling CoffeeScript and JavaScript asset compression requires youhave a JavaScript runtime available on your system, in the absenceof a runtime you will see an execjs error during asset compilation.Usually Mac OS X and Windows come with a JavaScript runtime installed.Rails adds the therubyracer gem to the generated Gemfile in acommented line for new apps and you can uncomment if you need it.therubyrhino is the recommended runtime for JRuby users and is added bydefault to the Gemfile in apps generated under JRuby. You can investigateall the supported runtimes at ExecJS.

This will fire up WEBrick, a web server distributed with Ruby by default. To seeyour application in action, open a browser window and navigate tohttp://localhost:3000. You should see the Rails default information page:

Getting Started with Rails — Ruby on Rails Guides (1)

To stop the web server, hit Ctrl+C in the terminal window where it'srunning. To verify the server has stopped you should see your command promptcursor again. For most UNIX-like systems including Mac OS X this will be adollar sign $. In development mode, Rails does not generally require you torestart the server; changes you make in files will be automatically picked up bythe server.

The "Welcome aboard" page is the smoke test for a new Rails application: itmakes sure that you have your software configured correctly enough to serve apage. You can also click on the About your application's environment link tosee a summary of your application's environment.

4.2 Say "Hello", Rails

To get Rails saying "Hello", you need to create at minimum a controller and aview.

A controller's purpose is to receive specific requests for the application.Routing decides which controller receives which requests. Often, there is morethan one route to each controller, and different routes can be served bydifferent actions. Each action's purpose is to collect information to provideit to a view.

A view's purpose is to display this information in a human readable format. Animportant distinction to make is that it is the controller, not the view,where information is collected. The view should just display that information.By default, view templates are written in a language called eRuby (EmbeddedRuby) which is processed by the request cycle in Rails before being sent to theuser.

To create a new controller, you will need to run the "controller" generator andtell it you want a controller called "welcome" with an action called "index",just like this:

$ bin/rails generate controller welcome index

Rails will create several files and a route for you.

create app/controllers/welcome_controller.rb route get 'welcome/index'invoke erbcreate app/views/welcomecreate app/views/welcome/index.html.erbinvoke test_unitcreate test/controllers/welcome_controller_test.rbinvoke helpercreate app/helpers/welcome_helper.rbinvoke assetsinvoke coffeecreate app/assets/javascripts/welcome.js.coffeeinvoke scsscreate app/assets/stylesheets/welcome.css.scss

Most important of these are of course the controller, located atapp/controllers/welcome_controller.rb and the view, located atapp/views/welcome/index.html.erb.

Open the app/views/welcome/index.html.erb file in your text editor. Delete allof the existing code in the file, and replace it with the following single lineof code:

<h1>Hello, Rails!</h1>

4.3 Setting the Application Home Page

Now that we have made the controller and view, we need to tell Rails when wewant "Hello, Rails!" to show up. In our case, we want it to show up when wenavigate to the root URL of our site, http://localhost:3000. At the moment,"Welcome aboard" is occupying that spot.

Next, you have to tell Rails where your actual home page is located.

Open the file config/routes.rb in your editor.

Rails.application.routes.draw do get 'welcome/index' # The priority is based upon order of creation: # first created -> highest priority. # # You can have the root of your site routed with "root" # root 'welcome#index' # # ...

This is your application's routing file which holds entries in a special DSL(domain-specific language) that tells Rails how to connect incoming requests tocontrollers and actions. This file contains many sample routes on commentedlines, and one of them actually shows you how to connect the root of your siteto a specific controller and action. Find the line beginning with root anduncomment it. It should look something like the following:

root 'welcome#index'

root 'welcome#index' tells Rails to map requests to the root of theapplication to the welcome controller's index action and get 'welcome/index'tells Rails to map requests to http://localhost:3000/welcome/index to thewelcome controller's index action. This was created earlier when you ran thecontroller generator (bin/rails generate controller welcome index).

Launch the web server again if you stopped it to generate the controller (bin/railsserver) and navigate to http://localhost:3000 in your browser. You'll see the"Hello, Rails!" message you put into app/views/welcome/index.html.erb,indicating that this new route is indeed going to WelcomeController's indexaction and is rendering the view correctly.

For more information about routing, refer to Rails Routing from the Outside In.

5 Getting Up and Running

Now that you've seen how to create a controller, an action and a view, let'screate something with a bit more substance.

In the Blog application, you will now create a new resource. A resource is theterm used for a collection of similar objects, such as articles, people oranimals.You can create, read, update and destroy items for a resource and theseoperations are referred to as CRUD operations.

Rails provides a resources method which can be used to declare a standard RESTresource. You need to add the article resource to theconfig/routes.rb as follows:

Rails.application.routes.draw do resources :articles root 'welcome#index'end

If you run bin/rake routes, you'll see that it has defined routes for all thestandard RESTful actions. The meaning of the prefix column (and other columns)will be seen later, but for now notice that Rails has inferred thesingular form article and makes meaningful use of the distinction.

$ bin/rake routes Prefix Verb URI Pattern Controller#Action articles GET /articles(.:format) articles#index POST /articles(.:format) articles#create new_article GET /articles/new(.:format) articles#newedit_article GET /articles/:id/edit(.:format) articles#edit article GET /articles/:id(.:format) articles#show PATCH /articles/:id(.:format) articles#update PUT /articles/:id(.:format) articles#update DELETE /articles/:id(.:format) articles#destroy root GET / welcome#index

In the next section, you will add the ability to create new articles in yourapplication and be able to view them. This is the "C" and the "R" from CRUD:creation and reading. The form for doing this will look like this:

Getting Started with Rails — Ruby on Rails Guides (2)

It will look a little basic for now, but that's ok. We'll look at improving thestyling for it afterwards.

5.1 Laying down the ground work

Firstly, you need a place within the application to create a new article. Agreat place for that would be at /articles/new. With the route alreadydefined, requests can now be made to /articles/new in the application.Navigate to http://localhost:3000/articles/new and you'll see a routingerror:

Getting Started with Rails — Ruby on Rails Guides (3)

This error occurs because the route needs to have a controller defined in orderto serve the request. The solution to this particular problem is simple: createa controller called ArticlesController. You can do this by running thiscommand:

$ bin/rails generate controller articles

If you open up the newly generated app/controllers/articles_controller.rbyou'll see a fairly empty controller:

class ArticlesController < ApplicationControllerend

A controller is simply a class that is defined to inherit fromApplicationController.It's inside this class that you'll define methods that will become the actionsfor this controller. These actions will perform CRUD operations on the articleswithin our system.

There are public, private and protected methods in Ruby,but only public methods can be actions for controllers.For more details check out Programming Ruby.

If you refresh http://localhost:3000/articles/new now, you'll get a new error:

Getting Started with Rails — Ruby on Rails Guides (4)

This error indicates that Rails cannot find the new action inside theArticlesController that you just generated. This is because when controllersare generated in Rails they are empty by default, unless you tell ityour wanted actions during the generation process.

To manually define an action inside a controller, all you need to do is todefine a new method inside the controller. Openapp/controllers/articles_controller.rb and inside the ArticlesControllerclass, define a new method so that the controller now looks like this:

With the new method defined in ArticlesController, if you refreshhttp://localhost:3000/articles/new you'll see another error:

Getting Started with Rails — Ruby on Rails Guides (5)

You're getting this error now because Rails expects plain actions like this oneto have views associated with them to display their information. With no viewavailable, Rails errors out.

In the above image, the bottom line has been truncated. Let's see what the fullthing looks like:

Missing template articles/new, application/new with {locale:[:en], formats:[:html], handlers:[:erb, :builder, :coffee]}. Searched in: * "/path/to/blog/app/views"

That's quite a lot of text! Let's quickly go through and understand what eachpart of it does.

The first part identifies what template is missing. In this case, it's thearticles/new template. Rails will first look for this template. If not found,then it will attempt to load a template called application/new. It looks forone here because the ArticlesController inherits from ApplicationController.

The next part of the message contains a hash. The :locale key in this hashsimply indicates what spoken language template should be retrieved. By default,this is the English - or "en" - template. The next key, :formats specifies theformat of template to be served in response. The default format is :html, andso Rails is looking for an HTML template. The final key, :handlers, is tellingus what template handlers could be used to render our template. :erb is mostcommonly used for HTML templates, :builder is used for XML templates, and:coffee uses CoffeeScript to build JavaScript templates.

The final part of this message tells us where Rails has looked for the templates.Templates within a basic Rails application like this are kept in a singlelocation, but in more complex applications it could be many different paths.

The simplest template that would work in this case would be one located atapp/views/articles/new.html.erb. The extension of this file name is key: thefirst extension is the format of the template, and the second extension is thehandler that will be used. Rails is attempting to find a template calledarticles/new within app/views for the application. The format for thistemplate can only be html and the handler must be one of erb, builder orcoffee. Because you want to create a new HTML form, you will be using the ERBlanguage. Therefore the file should be called articles/new.html.erb and needsto be located inside the app/views directory of the application.

Go ahead now and create a new file at app/views/articles/new.html.erb andwrite this content in it:

<h1>New Article</h1>

When you refresh http://localhost:3000/articles/new you'll now see that thepage has a title. The route, controller, action and view are now workingharmoniously! It's time to create the form for a new article.

5.2 The first form

To create a form within this template, you will use a formbuilder. The primary form builder for Rails is provided by a helpermethod called form_for. To use this method, add this code intoapp/views/articles/new.html.erb:

<%= form_for :article do |f| %> <p> <%= f.label :title %><br> <%= f.text_field :title %> </p> <p> <%= f.label :text %><br> <%= f.text_area :text %> </p> <p> <%= f.submit %> </p><% end %>

If you refresh the page now, you'll see the exact same form as in the example.Building forms in Rails is really just that easy!

When you call form_for, you pass it an identifying object for thisform. In this case, it's the symbol :article. This tells the form_forhelper what this form is for. Inside the block for this method, theFormBuilder object - represented by f - is used to build two labels and twotext fields, one each for the title and text of an article. Finally, a call tosubmit on the f object will create a submit button for the form.

There's one problem with this form though. If you inspect the HTML that isgenerated, by viewing the source of the page, you will see that the actionattribute for the form is pointing at /articles/new. This is a problem becausethis route goes to the very page that you're on right at the moment, and thatroute should only be used to display the form for a new article.

The form needs to use a different URL in order to go somewhere else.This can be done quite simply with the :url option of form_for.Typically in Rails, the action that is used for new form submissionslike this is called "create", and so the form should be pointed to that action.

Edit the form_for line inside app/views/articles/new.html.erb to look likethis:

<%= form_for :article, url: articles_path do |f| %>

In this example, the articles_path helper is passed to the :url option.To see what Rails will do with this, we look back at the output ofbin/rake routes:

$ bin/rake routes Prefix Verb URI Pattern Controller#Action articles GET /articles(.:format) articles#index POST /articles(.:format) articles#create new_article GET /articles/new(.:format) articles#newedit_article GET /articles/:id/edit(.:format) articles#edit article GET /articles/:id(.:format) articles#show PATCH /articles/:id(.:format) articles#update PUT /articles/:id(.:format) articles#update DELETE /articles/:id(.:format) articles#destroy root GET / welcome#index

The articles_path helper tells Rails to point the form to the URI Patternassociated with the articles prefix; and the form will (by default) send aPOST request to that route. This is associated with the create action ofthe current controller, the ArticlesController.

With the form and its associated route defined, you will be able to fill in theform and then click the submit button to begin the process of creating a newarticle, so go ahead and do that. When you submit the form, you should see afamiliar error:

Getting Started with Rails — Ruby on Rails Guides (6)

You now need to create the create action within the ArticlesController forthis to work.

5.3 Creating articles

To make the "Unknown action" go away, you can define a create action withinthe ArticlesController class in app/controllers/articles_controller.rb,underneath the new action, as shown:

class ArticlesController < ApplicationController def new end def create endend

If you re-submit the form now, you'll see another familiar error: a template ismissing. That's ok, we can ignore that for now. What the create action shouldbe doing is saving our new article to the database.

When a form is submitted, the fields of the form are sent to Rails asparameters. These parameters can then be referenced inside the controlleractions, typically to perform a particular task. To see what these parameterslook like, change the create action to this:

def create render plain: params[:article].inspectend

The render method here is taking a very simple hash with a key of plain andvalue of params[:article].inspect. The params method is the object whichrepresents the parameters (or fields) coming in from the form. The paramsmethod returns an ActiveSupport::HashWithIndifferentAccess object, whichallows you to access the keys of the hash using either strings or symbols. Inthis situation, the only parameters that matter are the ones from the form.

Ensure you have a firm grasp of the params method, as you'll use it fairly regularly. Let's consider an example URL: http://www.example.com/?username=dhh&email=dhh@email.com. In this URL, params[:username] would equal "dhh" and params[:email] would equal "dhh@email.com".

If you re-submit the form one more time you'll now no longer get the missingtemplate error. Instead, you'll see something that looks like the following:

{"title"=>"First article!", "text"=>"This is my first article."}

This action is now displaying the parameters for the article that are coming infrom the form. However, this isn't really all that helpful. Yes, you can see theparameters but nothing in particular is being done with them.

5.4 Creating the Article model

Models in Rails use a singular name, and their corresponding database tablesuse a plural name. Rails provides a generator for creating models, which mostRails developers tend to use when creating new models. To create the new model,run this command in your terminal:

$ bin/rails generate model Article title:string text:text

With that command we told Rails that we want a Article model, togetherwith a title attribute of type string, and a text attributeof type text. Those attributes are automatically added to the articlestable in the database and mapped to the Article model.

Rails responded by creating a bunch of files. For now, we're only interestedin app/models/article.rb and db/migrate/20140120191729_create_articles.rb(your name could be a bit different). The latter is responsible for creatingthe database structure, which is what we'll look at next.

Active Record is smart enough to automatically map column names to modelattributes, which means you don't have to declare attributes inside Railsmodels, as that will be done automatically by Active Record.

5.5 Running a Migration

As we've just seen, bin/rails generate model created a database migration fileinside the db/migrate directory. Migrations are Ruby classes that aredesigned to make it simple to create and modify database tables. Rails usesrake commands to run migrations, and it's possible to undo a migration afterit's been applied to your database. Migration filenames include a timestamp toensure that they're processed in the order that they were created.

If you look in the db/migrate/20140120191729_create_articles.rb file (remember,yours will have a slightly different name), here's what you'll find:

class CreateArticles < ActiveRecord::Migration def change create_table :articles do |t| t.string :title t.text :text t.timestamps null: false end endend

The above migration creates a method named change which will be called whenyou run this migration. The action defined in this method is also reversible,which means Rails knows how to reverse the change made by this migration,in case you want to reverse it later. When you run this migration it will createan articles table with one string column and a text column. It also createstwo timestamp fields to allow Rails to track article creation and update times.

For more information about migrations, refer to Rails Database Migrations.

At this point, you can use a rake command to run the migration:

$ bin/rake db:migrate

Rails will execute this migration command and tell you it created the Articlestable.

== CreateArticles: migrating ==================================================-- create_table(:articles) -> 0.0019s== CreateArticles: migrated (0.0020s) =========================================

Because you're working in the development environment by default, thiscommand will apply to the database defined in the development section of yourconfig/database.yml file. If you would like to execute migrations in anotherenvironment, for instance in production, you must explicitly pass it wheninvoking the command: bin/rake db:migrate RAILS_ENV=production.

5.6 Saving data in the controller

Back in ArticlesController, we need to change the create actionto use the new Article model to save the data in the database.Open app/controllers/articles_controller.rb and change the create action tolook like this:

def create @article = Article.new(params[:article]) @article.save redirect_to @articleend

Here's what's going on: every Rails model can be initialized with itsrespective attributes, which are automatically mapped to the respectivedatabase columns. In the first line we do just that (remember thatparams[:article] contains the attributes we're interested in). Then,@article.save is responsible for saving the model in the database. Finally,we redirect the user to the show action, which we'll define later.

You might be wondering why the A in Article.new is capitalized above, whereas most other references to articles in this guide have used lowercase. In this context, we are referring to the class named Article that is defined in \models\article.rb. Class names in Ruby must begin with a capital letter.

As we'll see later, @article.save returns a boolean indicating whetherthe article was saved or not.

If you now go to http://localhost:3000/articles/new you'll almost be ableto create an article. Try it! You should get an error that looks like this:

Getting Started with Rails — Ruby on Rails Guides (7)

Rails has several security features that help you write secure applications,and you're running into one of them now. This one is called strong parameters,which requires us to tell Rails exactly which parameters are allowed into ourcontroller actions.

Why do you have to bother? The ability to grab and automatically assign allcontroller parameters to your model in one shot makes the programmer's jobeasier, but this convenience also allows malicious use. What if a request tothe server was crafted to look like a new article form submit but also includedextra fields with values that violated your applications integrity? They wouldbe 'mass assigned' into your model and then into the database along with thegood stuff - potentially breaking your application or worse.

We have to whitelist our controller parameters to prevent wrongful massassignment. In this case, we want to both allow and require the title andtext parameters for valid use of create. The syntax for this introducesrequire and permit. The change will involve one line in the create action:

 @article = Article.new(params.require(:article).permit(:title, :text))

This is often factored out into its own method so it can be reused by multipleactions in the same controller, for example create and update. Above andbeyond mass assignment issues, the method is often made private to make sureit can't be called outside its intended context. Here is the result:

def create @article = Article.new(article_params) @article.save redirect_to @articleendprivate def article_params params.require(:article).permit(:title, :text) end

For more information, refer to the reference above andthis blog article about Strong Parameters.

5.7 Showing Articles

If you submit the form again now, Rails will complain about not finding theshow action. That's not very useful though, so let's add the show actionbefore proceeding.

As we have seen in the output of bin/rake routes, the route for show action isas follows:

article GET /articles/:id(.:format) articles#show

The special syntax :id tells rails that this route expects an :idparameter, which in our case will be the id of the article.

As we did before, we need to add the show action inapp/controllers/articles_controller.rb and its respective view.

A frequent practice is to place the standard CRUD actions in eachcontroller in the following order: index, show, new, edit, create, updateand destroy. You may use any order you choose, but keep in mind that theseare public methods; as mentioned earlier in this guide, they must be placedbefore any private or protected method in the controller in order to work.

Given that, let's add the show action, as follows:

class ArticlesController < ApplicationController def show @article = Article.find(params[:id]) end def new end # snippet for brevity

A couple of things to note. We use Article.find to find the article we'reinterested in, passing in params[:id] to get the :id parameter from therequest. We also use an instance variable (prefixed with @) to hold areference to the article object. We do this because Rails will pass all instancevariables to the view.

Now, create a new file app/views/articles/show.html.erb with the followingcontent:

<p> <strong>Title:</strong> <%= @article.title %></p><p> <strong>Text:</strong> <%= @article.text %></p>

With this change, you should finally be able to create new articles.Visit http://localhost:3000/articles/new and give it a try!

Getting Started with Rails — Ruby on Rails Guides (8)

5.8 Listing all articles

We still need a way to list all our articles, so let's do that.The route for this as per output of bin/rake routes is:

articles GET /articles(.:format) articles#index

Add the corresponding index action for that route inside theArticlesController in the app/controllers/articles_controller.rb file.When we write an index action, the usual practice is to place it as thefirst method in the controller. Let's do it:

class ArticlesController < ApplicationController def index @articles = Article.all end def show @article = Article.find(params[:id]) end def new end # snippet for brevity

And then finally, add the view for this action, located atapp/views/articles/index.html.erb:

<h1>Listing articles</h1><table> <tr> <th>Title</th> <th>Text</th> </tr> <% @articles.each do |article| %> <tr> <td><%= article.title %></td> <td><%= article.text %></td> </tr> <% end %></table>

Now if you go to http://localhost:3000/articles you will see a list of all thearticles that you have created.

5.9 Adding links

You can now create, show, and list articles. Now let's add some links tonavigate through pages.

Open app/views/welcome/index.html.erb and modify it as follows:

<h1>Hello, Rails!</h1><%= link_to 'My Blog', controller: 'articles' %>

The link_to method is one of Rails' built-in view helpers. It creates ahyperlink based on text to display and where to go - in this case, to the pathfor articles.

Let's add links to the other views as well, starting with adding this"New Article" link to app/views/articles/index.html.erb, placing it above the<table> tag:

<%= link_to 'New article', new_article_path %>

This link will allow you to bring up the form that lets you create a new article.

Now, add another link in app/views/articles/new.html.erb, underneath theform, to go back to the index action:

<%= form_for :article, url: articles_path do |f| %> ...<% end %><%= link_to 'Back', articles_path %>

Finally, add a link to the app/views/articles/show.html.erb template togo back to the index action as well, so that people who are viewing a singlearticle can go back and view the whole list again:

<p> <strong>Title:</strong> <%= @article.title %></p><p> <strong>Text:</strong> <%= @article.text %></p><%= link_to 'Back', articles_path %>

If you want to link to an action in the same controller, you don't need tospecify the :controller option, as Rails will use the current controller bydefault.

In development mode (which is what you're working in by default), Railsreloads your application with every browser request, so there's no need to stopand restart the web server when a change is made.

5.10 Adding Some Validation

The model file, app/models/article.rb is about as simple as it can get:

class Article < ActiveRecord::Baseend

There isn't much to this file - but note that the Article class inherits fromActiveRecord::Base. Active Record supplies a great deal of functionality toyour Rails models for free, including basic database CRUD (Create, Read, Update,Destroy) operations, data validation, as well as sophisticated search supportand the ability to relate multiple models to one another.

Rails includes methods to help you validate the data that you send to models.Open the app/models/article.rb file and edit it:

class Article < ActiveRecord::Base validates :title, presence: true, length: { minimum: 5 }end

These changes will ensure that all articles have a title that is at least fivecharacters long. Rails can validate a variety of conditions in a model,including the presence or uniqueness of columns, their format, and theexistence of associated objects. Validations are covered in detail in ActiveRecord Validations.

With the validation now in place, when you call @article.save on an invalidarticle, it will return false. If you openapp/controllers/articles_controller.rb again, you'll notice that we don'tcheck the result of calling @article.save inside the create action.If @article.save fails in this situation, we need to show the form back to theuser. To do this, change the new and create actions insideapp/controllers/articles_controller.rb to these:

def new @article = Article.newenddef create @article = Article.new(article_params) if @article.save redirect_to @article else render 'new' endendprivate def article_params params.require(:article).permit(:title, :text) end

The new action is now creating a new instance variable called @article, andyou'll see why that is in just a few moments.

Notice that inside the create action we use render instead of redirect_towhen save returns false. The render method is used so that the @articleobject is passed back to the new template when it is rendered. This renderingis done within the same request as the form submission, whereas theredirect_to will tell the browser to issue another request.

If you reloadhttp://localhost:3000/articles/new andtry to save an article without a title, Rails will send you back to theform, but that's not very useful. You need to tell the user thatsomething went wrong. To do that, you'll modifyapp/views/articles/new.html.erb to check for error messages:

<%= form_for :article, url: articles_path do |f| %> <% if @article.errors.any? %> <div id="error_explanation"> <h2> <%= pluralize(@article.errors.count, "error") %> prohibited this article from being saved: </h2> <ul> <% @article.errors.full_messages.each do |msg| %> <li><%= msg %></li> <% end %> </ul> </div> <% end %> <p> <%= f.label :title %><br> <%= f.text_field :title %> </p> <p> <%= f.label :text %><br> <%= f.text_area :text %> </p> <p> <%= f.submit %> </p><% end %><%= link_to 'Back', articles_path %>

A few things are going on. We check if there are any errors with@article.errors.any?, and in that case we show a list of allerrors with @article.errors.full_messages.

pluralize is a rails helper that takes a number and a string as itsarguments. If the number is greater than one, the string will be automaticallypluralized.

The reason why we added @article = Article.new in the ArticlesController isthat otherwise @article would be nil in our view, and calling@article.errors.any? would throw an error.

Rails automatically wraps fields that contain an error with a divwith class field_with_errors. You can define a css rule to make themstandout.

Now you'll get a nice error message when saving an article without title whenyou attempt to do just that on the new article formhttp://localhost:3000/articles/new:

Getting Started with Rails — Ruby on Rails Guides (9)

5.11 Updating Articles

We've covered the "CR" part of CRUD. Now let's focus on the "U" part, updatingarticles.

The first step we'll take is adding an edit action to the ArticlesController,generally between the new and create actions, as shown:

def new @article = Article.newenddef edit @article = Article.find(params[:id])enddef create @article = Article.new(article_params) if @article.save redirect_to @article else render 'new' endend

The view will contain a form similar to the one we used when creatingnew articles. Create a file called app/views/articles/edit.html.erb and makeit look as follows:

<h1>Editing article</h1><%= form_for :article, url: article_path(@article), method: :patch do |f| %> <% if @article.errors.any? %> <div id="error_explanation"> <h2> <%= pluralize(@article.errors.count, "error") %> prohibited this article from being saved: </h2> <ul> <% @article.errors.full_messages.each do |msg| %> <li><%= msg %></li> <% end %> </ul> </div> <% end %> <p> <%= f.label :title %><br> <%= f.text_field :title %> </p> <p> <%= f.label :text %><br> <%= f.text_area :text %> </p> <p> <%= f.submit %> </p><% end %><%= link_to 'Back', articles_path %>

This time we point the form to the update action, which is not defined yetbut will be very soon.

The method: :patch option tells Rails that we want this form to be submittedvia the PATCH HTTP method which is the HTTP method you're expected to use toupdate resources according to the REST protocol.

The first parameter of form_for can be an object, say, @article which wouldcause the helper to fill in the form with the fields of the object. Passing in asymbol (:article) with the same name as the instance variable (@article)also automagically leads to the same behavior. This is what is happening here.More details can be found in form_for documentation.

Next, we need to create the update action inapp/controllers/articles_controller.rb.Add it between the create action and the private method:

def create @article = Article.new(article_params) if @article.save redirect_to @article else render 'new' endenddef update @article = Article.find(params[:id]) if @article.update(article_params) redirect_to @article else render 'edit' endendprivate def article_params params.require(:article).permit(:title, :text) end

The new method, update, is used when you want to update a recordthat already exists, and it accepts a hash containing the attributesthat you want to update. As before, if there was an error updating thearticle we want to show the form back to the user.

We reuse the article_params method that we defined earlier for the createaction.

You don't need to pass all attributes to update. Forexample, if you'd call @article.update(title: 'A new title')Rails would only update the title attribute, leaving all otherattributes untouched.

Finally, we want to show a link to the edit action in the list of all thearticles, so let's add that now to app/views/articles/index.html.erb to makeit appear next to the "Show" link:

<table> <tr> <th>Title</th> <th>Text</th> <th colspan="2"></th> </tr> <% @articles.each do |article| %> <tr> <td><%= article.title %></td> <td><%= article.text %></td> <td><%= link_to 'Show', article_path(article) %></td> <td><%= link_to 'Edit', edit_article_path(article) %></td> </tr> <% end %></table>

And we'll also add one to the app/views/articles/show.html.erb template aswell, so that there's also an "Edit" link on an article's page. Add this at thebottom of the template:

...<%= link_to 'Edit', edit_article_path(@article) %> |<%= link_to 'Back', articles_path %>

And here's how our app looks so far:

Getting Started with Rails — Ruby on Rails Guides (10)

5.12 Using partials to clean up duplication in views

Our edit page looks very similar to the new page; in fact, theyboth share the same code for displaying the form. Let's remove thisduplication by using a view partial. By convention, partial files areprefixed with an underscore.

You can read more about partials in theLayouts and Rendering in Rails guide.

Create a new file app/views/articles/_form.html.erb with the followingcontent:

<%= form_for @article do |f| %> <% if @article.errors.any? %> <div id="error_explanation"> <h2> <%= pluralize(@article.errors.count, "error") %> prohibited this article from being saved: </h2> <ul> <% @article.errors.full_messages.each do |msg| %> <li><%= msg %></li> <% end %> </ul> </div> <% end %> <p> <%= f.label :title %><br> <%= f.text_field :title %> </p> <p> <%= f.label :text %><br> <%= f.text_area :text %> </p> <p> <%= f.submit %> </p><% end %>

Everything except for the form_for declaration remained the same.The reason we can use this shorter, simpler form_for declarationto stand in for either of the other forms is that @article is a resourcecorresponding to a full set of RESTful routes, and Rails is able to inferwhich URI and method to use.For more information about this use of form_for, see Resource-oriented style.

Now, let's update the app/views/articles/new.html.erb view to use this newpartial, rewriting it completely:

<h1>New article</h1><%= render 'form' %><%= link_to 'Back', articles_path %>

Then do the same for the app/views/articles/edit.html.erb view:

<h1>Edit article</h1><%= render 'form' %><%= link_to 'Back', articles_path %>

5.13 Deleting Articles

We're now ready to cover the "D" part of CRUD, deleting articles from thedatabase. Following the REST convention, the route fordeleting articles as per output of bin/rake routes is:

DELETE /articles/:id(.:format) articles#destroy

The delete routing method should be used for routes that destroyresources. If this was left as a typical get route, it could be possible forpeople to craft malicious URLs like this:

<a href='http://example.com/articles/1/destroy'>look at this cat!</a>

We use the delete method for destroying resources, and this route is mappedto the destroy action inside app/controllers/articles_controller.rb, whichdoesn't exist yet. The destroy method is generally the last CRUD action inthe controller, and like the other public CRUD actions, it must be placedbefore any private or protected methods. Let's add it:

def destroy @article = Article.find(params[:id]) @article.destroy redirect_to articles_pathend

The complete ArticlesController in theapp/controllers/articles_controller.rb file should now look like this:

class ArticlesController < ApplicationController def index @articles = Article.all end def show @article = Article.find(params[:id]) end def new @article = Article.new end def edit @article = Article.find(params[:id]) end def create @article = Article.new(article_params) if @article.save redirect_to @article else render 'new' end end def update @article = Article.find(params[:id]) if @article.update(article_params) redirect_to @article else render 'edit' end end def destroy @article = Article.find(params[:id]) @article.destroy redirect_to articles_path end private def article_params params.require(:article).permit(:title, :text) endend

You can call destroy on Active Record objects when you want to deletethem from the database. Note that we don't need to add a view for thisaction since we're redirecting to the index action.

Finally, add a 'Destroy' link to your index action template(app/views/articles/index.html.erb) to wrap everything together.

<h1>Listing Articles</h1><%= link_to 'New article', new_article_path %><table> <tr> <th>Title</th> <th>Text</th> <th colspan="3"></th> </tr> <% @articles.each do |article| %> <tr> <td><%= article.title %></td> <td><%= article.text %></td> <td><%= link_to 'Show', article_path(article) %></td> <td><%= link_to 'Edit', edit_article_path(article) %></td> <td><%= link_to 'Destroy', article_path(article), method: :delete, data: { confirm: 'Are you sure?' } %></td> </tr> <% end %></table>

Here we're using link_to in a different way. We pass the named route as thesecond argument, and then the options as another argument. The :method and:'data-confirm' options are used as HTML5 attributes so that when the link isclicked, Rails will first show a confirm dialog to the user, and then submit thelink with method delete. This is done via the JavaScript file jquery_ujswhich is automatically included into your application's layout(app/views/layouts/application.html.erb) when you generated the application.Without this file, the confirmation dialog box wouldn't appear.

Getting Started with Rails — Ruby on Rails Guides (11)

Congratulations, you can now create, show, list, update and destroyarticles.

In general, Rails encourages using resources objects instead ofdeclaring routes manually. For more information about routing, seeRails Routing from the Outside In.

6 Adding a Second Model

It's time to add a second model to the application. The second model will handlecomments on articles.

6.1 Generating a Model

We're going to see the same generator that we used before when creatingthe Article model. This time we'll create a Comment model to holdreference of article comments. Run this command in your terminal:

$ bin/rails generate model Comment commenter:string body:text article:references

This command will generate four files:

FilePurpose
db/migrate/20140120201010_create_comments.rbMigration to create the comments table in your database (your name will include a different timestamp)
app/models/comment.rbThe Comment model
test/models/comment_test.rbTesting harness for the comments model
test/fixtures/comments.ymlSample comments for use in testing

First, take a look at app/models/comment.rb:

class Comment < ActiveRecord::Base belongs_to :articleend

This is very similar to the Article model that you saw earlier. The differenceis the line belongs_to :article, which sets up an Active Record association.You'll learn a little about associations in the next section of this guide.

In addition to the model, Rails has also made a migration to create thecorresponding database table:

class CreateComments < ActiveRecord::Migration def change create_table :comments do |t| t.string :commenter t.text :body t.references :article, index: true, foreign_key: true t.timestamps null: false end endend

The t.references line creates an integer column called article_id, an indexfor it, and a foreign key constraint that points to the articles table. Goahead and run the migration:

$ bin/rake db:migrate

Rails is smart enough to only execute the migrations that have not already beenrun against the current database, so in this case you will just see:

== CreateComments: migrating =================================================-- create_table(:comments) -> 0.0115s== CreateComments: migrated (0.0119s) ========================================

6.2 Associating Models

Active Record associations let you easily declare the relationship between twomodels. In the case of comments and articles, you could write out therelationships this way:

  • Each comment belongs to one article.
  • One article can have many comments.

In fact, this is very close to the syntax that Rails uses to declare thisassociation. You've already seen the line of code inside the Comment model(app/models/comment.rb) that makes each comment belong to an Article:

class Comment < ActiveRecord::Base belongs_to :articleend

You'll need to edit app/models/article.rb to add the other side of theassociation:

class Article < ActiveRecord::Base has_many :comments validates :title, presence: true, length: { minimum: 5 }end

These two declarations enable a good bit of automatic behavior. For example, ifyou have an instance variable @article containing an article, you can retrieveall the comments belonging to that article as an array using@article.comments.

For more information on Active Record associations, see the Active RecordAssociations guide.

6.3 Adding a Route for Comments

As with the welcome controller, we will need to add a route so that Railsknows where we would like to navigate to see comments. Open up theconfig/routes.rb file again, and edit it as follows:

resources :articles do resources :commentsend

This creates comments as a nested resource within articles. This isanother part of capturing the hierarchical relationship that exists betweenarticles and comments.

For more information on routing, see the Rails Routingguide.

6.4 Generating a Controller

With the model in hand, you can turn your attention to creating a matchingcontroller. Again, we'll use the same generator we used before:

$ bin/rails generate controller Comments

This creates five files and one empty directory:

File/DirectoryPurpose
app/controllers/comments_controller.rbThe Comments controller
app/views/comments/Views of the controller are stored here
test/controllers/comments_controller_test.rbThe test for the controller
app/helpers/comments_helper.rbA view helper file
app/assets/javascripts/comment.js.coffeeCoffeeScript for the controller
app/assets/stylesheets/comment.css.scssCascading style sheet for the controller

Like with any blog, our readers will create their comments directly afterreading the article, and once they have added their comment, will be sent backto the article show page to see their comment now listed. Due to this, ourCommentsController is there to provide a method to create comments and deletespam comments when they arrive.

So first, we'll wire up the Article show template(app/views/articles/show.html.erb) to let us make a new comment:

<p> <strong>Title:</strong> <%= @article.title %></p><p> <strong>Text:</strong> <%= @article.text %></p><h2>Add a comment:</h2><%= form_for([@article, @article.comments.build]) do |f| %> <p> <%= f.label :commenter %><br> <%= f.text_field :commenter %> </p> <p> <%= f.label :body %><br> <%= f.text_area :body %> </p> <p> <%= f.submit %> </p><% end %><%= link_to 'Edit', edit_article_path(@article) %> |<%= link_to 'Back', articles_path %>

This adds a form on the Article show page that creates a new comment bycalling the CommentsController create action. The form_for call here usesan array, which will build a nested route, such as /articles/1/comments.

Let's wire up the create in app/controllers/comments_controller.rb:

class CommentsController < ApplicationController def create @article = Article.find(params[:article_id]) @comment = @article.comments.create(comment_params) redirect_to article_path(@article) end private def comment_params params.require(:comment).permit(:commenter, :body) endend

You'll see a bit more complexity here than you did in the controller forarticles. That's a side-effect of the nesting that you've set up. Each requestfor a comment has to keep track of the article to which the comment is attached,thus the initial call to the find method of the Article model to get thearticle in question.

In addition, the code takes advantage of some of the methods available for anassociation. We use the create method on @article.comments to create andsave the comment. This will automatically link the comment so that it belongs tothat particular article.

Once we have made the new comment, we send the user back to the original articleusing the article_path(@article) helper. As we have already seen, this callsthe show action of the ArticlesController which in turn renders theshow.html.erb template. This is where we want the comment to show, so let'sadd that to the app/views/articles/show.html.erb.

<p> <strong>Title:</strong> <%= @article.title %></p><p> <strong>Text:</strong> <%= @article.text %></p><h2>Comments</h2><% @article.comments.each do |comment| %> <p> <strong>Commenter:</strong> <%= comment.commenter %> </p> <p> <strong>Comment:</strong> <%= comment.body %> </p><% end %><h2>Add a comment:</h2><%= form_for([@article, @article.comments.build]) do |f| %> <p> <%= f.label :commenter %><br> <%= f.text_field :commenter %> </p> <p> <%= f.label :body %><br> <%= f.text_area :body %> </p> <p> <%= f.submit %> </p><% end %><%= link_to 'Edit', edit_article_path(@article) %> |<%= link_to 'Back', articles_path %>

Now you can add articles and comments to your blog and have them show up in theright places.

Getting Started with Rails — Ruby on Rails Guides (12)

7 Refactoring

Now that we have articles and comments working, take a look at theapp/views/articles/show.html.erb template. It is getting long and awkward. Wecan use partials to clean it up.

7.1 Rendering Partial Collections

First, we will make a comment partial to extract showing all the comments forthe article. Create the file app/views/comments/_comment.html.erb and put thefollowing into it:

<p> <strong>Commenter:</strong> <%= comment.commenter %></p><p> <strong>Comment:</strong> <%= comment.body %></p>

Then you can change app/views/articles/show.html.erb to look like thefollowing:

<p> <strong>Title:</strong> <%= @article.title %></p><p> <strong>Text:</strong> <%= @article.text %></p><h2>Comments</h2><%= render @article.comments %><h2>Add a comment:</h2><%= form_for([@article, @article.comments.build]) do |f| %> <p> <%= f.label :commenter %><br> <%= f.text_field :commenter %> </p> <p> <%= f.label :body %><br> <%= f.text_area :body %> </p> <p> <%= f.submit %> </p><% end %><%= link_to 'Edit', edit_article_path(@article) %> |<%= link_to 'Back', articles_path %>

This will now render the partial in app/views/comments/_comment.html.erb oncefor each comment that is in the @article.comments collection. As the rendermethod iterates over the @article.comments collection, it assigns eachcomment to a local variable named the same as the partial, in this casecomment which is then available in the partial for us to show.

7.2 Rendering a Partial Form

Let us also move that new comment section out to its own partial. Again, youcreate a file app/views/comments/_form.html.erb containing:

<%= form_for([@article, @article.comments.build]) do |f| %> <p> <%= f.label :commenter %><br> <%= f.text_field :commenter %> </p> <p> <%= f.label :body %><br> <%= f.text_area :body %> </p> <p> <%= f.submit %> </p><% end %>

Then you make the app/views/articles/show.html.erb look like the following:

<p> <strong>Title:</strong> <%= @article.title %></p><p> <strong>Text:</strong> <%= @article.text %></p><h2>Comments</h2><%= render @article.comments %><h2>Add a comment:</h2><%= render 'comments/form' %><%= link_to 'Edit', edit_article_path(@article) %> |<%= link_to 'Back', articles_path %>

The second render just defines the partial template we want to render,comments/form. Rails is smart enough to spot the forward slash in thatstring and realize that you want to render the _form.html.erb file inthe app/views/comments directory.

The @article object is available to any partials rendered in the view becausewe defined it as an instance variable.

8 Deleting Comments

Another important feature of a blog is being able to delete spam comments. To dothis, we need to implement a link of some sort in the view and a destroyaction in the CommentsController.

So first, let's add the delete link in theapp/views/comments/_comment.html.erb partial:

<p> <strong>Commenter:</strong> <%= comment.commenter %></p><p> <strong>Comment:</strong> <%= comment.body %></p><p> <%= link_to 'Destroy Comment', [comment.article, comment], method: :delete, data: { confirm: 'Are you sure?' } %></p>

Clicking this new "Destroy Comment" link will fire off a DELETE/articles/:article_id/comments/:id to our CommentsController, which can thenuse this to find the comment we want to delete, so let's add a destroy actionto our controller (app/controllers/comments_controller.rb):

class CommentsController < ApplicationController def create @article = Article.find(params[:article_id]) @comment = @article.comments.create(comment_params) redirect_to article_path(@article) end def destroy @article = Article.find(params[:article_id]) @comment = @article.comments.find(params[:id]) @comment.destroy redirect_to article_path(@article) end private def comment_params params.require(:comment).permit(:commenter, :body) endend

The destroy action will find the article we are looking at, locate the commentwithin the @article.comments collection, and then remove it from thedatabase and send us back to the show action for the article.

8.1 Deleting Associated Objects

If you delete an article, its associated comments will also need to bedeleted, otherwise they would simply occupy space in the database. Rails allowsyou to use the dependent option of an association to achieve this. Modify theArticle model, app/models/article.rb, as follows:

class Article < ActiveRecord::Base has_many :comments, dependent: :destroy validates :title, presence: true, length: { minimum: 5 }end

9 Security

9.1 Basic Authentication

If you were to publish your blog online, anyone would be able to add, edit anddelete articles or delete comments.

Rails provides a very simple HTTP authentication system that will work nicely inthis situation.

In the ArticlesController we need to have a way to block access to thevarious actions if the person is not authenticated. Here we can use the Railshttp_basic_authenticate_with method, which allows access to the requestedaction if that method allows it.

To use the authentication system, we specify it at the top of ourArticlesController in app/controllers/articles_controller.rb. In our case,we want the user to be authenticated on every action except index and show,so we write that:

class ArticlesController < ApplicationController http_basic_authenticate_with name: "dhh", password: "secret", except: [:index, :show] def index @articles = Article.all end # snippet for brevity

We also want to allow only authenticated users to delete comments, so in theCommentsController (app/controllers/comments_controller.rb) we write:

class CommentsController < ApplicationController http_basic_authenticate_with name: "dhh", password: "secret", only: :destroy def create @article = Article.find(params[:article_id]) # ... end # snippet for brevity

Now if you try to create a new article, you will be greeted with a basic HTTPAuthentication challenge:

Getting Started with Rails — Ruby on Rails Guides (13)

Other authentication methods are available for Rails applications. Two popularauthentication add-ons for Rails are theDevise rails engine andthe Authlogic gem,along with a number of others.

9.2 Other Security Considerations

Security, especially in web applications, is a broad and detailed area. Securityin your Rails application is covered in more depth inthe Ruby on Rails Security Guide.

10 What's Next?

Now that you've seen your first Rails application, you should feel free toupdate it and experiment on your own. But you don't have to do everythingwithout help. As you need assistance getting up and running with Rails, feelfree to consult these support resources:

Rails also comes with built-in help that you can generate using the rakecommand-line utility:

  • Running rake doc:guides will put a full copy of the Rails Guides in thedoc/guides folder of your application. Open doc/guides/index.html in yourweb browser to explore the Guides.
  • Running rake doc:rails will put a full copy of the API documentation forRails in the doc/api folder of your application. Open doc/api/index.htmlin your web browser to explore the API documentation.

To be able to generate the Rails Guides locally with the doc:guides raketask you need to install the RedCloth and Nokogiri gems. Add it to your Gemfile and runbundle install and you're ready to go.

11 Configuration Gotchas

The easiest way to work with Rails is to store all external data as UTF-8. Ifyou don't, Ruby libraries and Rails will often be able to convert your nativedata into UTF-8, but this doesn't always work reliably, so you're better offensuring that all external data is UTF-8.

If you have made a mistake in this area, the most common symptom is a blackdiamond with a question mark inside appearing in the browser. Another commonsymptom is characters like "ü" appearing instead of "ü". Rails takes a numberof internal steps to mitigate common causes of these problems that can beautomatically detected and corrected. However, if you have external data that isnot stored as UTF-8, it can occasionally result in these kinds of issues thatcannot be automatically detected by Rails and corrected.

Two very common sources of data that are not UTF-8:

  • Your text editor: Most text editors (such as TextMate), default to savingfiles as UTF-8. If your text editor does not, this can result in specialcharacters that you enter in your templates (such as é) to appear as a diamondwith a question mark inside in the browser. This also applies to your i18ntranslation files. Most editors that do not already default to UTF-8 (such assome versions of Dreamweaver) offer a way to change the default to UTF-8. Doso.
  • Your database: Rails defaults to converting data from your database into UTF-8at the boundary. However, if your database is not using UTF-8 internally, itmay not be able to store all characters that your users enter. For instance,if your database is using Latin-1 internally, and your user enters a Russian,Hebrew, or Japanese character, the data will be lost forever once it entersthe database. If possible, use UTF-8 as the internal storage of your database.

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 master. Make sure to check Edge Guides first to verify if the issues are already fixed or not on the master 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.

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

Getting Started with Rails — Ruby on Rails Guides (2024)
Top Articles
Latest Posts
Article information

Author: Kerri Lueilwitz

Last Updated:

Views: 6450

Rating: 4.7 / 5 (67 voted)

Reviews: 90% of readers found this page helpful

Author information

Name: Kerri Lueilwitz

Birthday: 1992-10-31

Address: Suite 878 3699 Chantelle Roads, Colebury, NC 68599

Phone: +6111989609516

Job: Chief Farming Manager

Hobby: Mycology, Stone skipping, Dowsing, Whittling, Taxidermy, Sand art, Roller skating

Introduction: My name is Kerri Lueilwitz, I am a courageous, gentle, quaint, thankful, outstanding, brave, vast person who loves writing and wants to share my knowledge and understanding with you.