2018-07-24 02:29:31 +00:00
**DO NOT READ THIS FILE ON GITHUB, GUIDES ARE PUBLISHED ON https://guides.rubyonrails.org.**
2014-12-23 22:32:50 +00:00
2012-10-17 13:15:55 +00:00
Getting Started with Rails
==========================
2012-11-29 22:25:02 +00:00
This guide covers getting up and running with Ruby on Rails.
After reading this guide, you will know:
2012-10-17 13:15:55 +00:00
2012-12-07 17:50:09 +00:00
* How to install Rails, create a new Rails application, and connect your
2012-10-17 13:15:55 +00:00
application to a database.
* The general layout of a Rails application.
* The basic principles of MVC (Model, View, Controller) and RESTful design.
* How to quickly generate the starting pieces of a Rails application.
--------------------------------------------------------------------------------
Guide Assumptions
-----------------
This guide is designed for beginners who want to get started with a Rails
application from scratch. It does not assume that you have any prior experience
2017-05-21 18:06:33 +00:00
with Rails.
2012-10-17 13:15:55 +00:00
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 learning
2014-01-02 05:25:40 +00:00
curve diving straight into Rails. There are several curated lists of online resources
for learning Ruby:
2012-10-17 13:15:55 +00:00
2014-01-02 05:25:40 +00:00
* [Official Ruby Programming Language website ](https://www.ruby-lang.org/en/documentation/ )
2019-06-27 02:53:46 +00:00
* [List of Free Programming Books ](https://github.com/EbookFoundation/free-programming-books/blob/master/free-programming-books.md#ruby )
2014-01-02 05:25:40 +00:00
2020-10-28 21:08:51 +00:00
Be aware that some resources, while still excellent, cover older versions of
Ruby, and may not include some syntax that you will see in day-to-day
2014-01-02 05:25:40 +00:00
development with Rails.
2012-10-17 13:15:55 +00:00
What is Rails?
--------------
2017-04-18 01:53:06 +00:00
Rails is a web application development framework written in the Ruby programming language.
2012-10-17 13:15:55 +00:00
It is designed to make programming web applications easier by making assumptions
about what every developer needs to get started. It allows you to write less
code while accomplishing more than many other languages and frameworks.
Experienced Rails developers also report that it makes web application
development more fun.
2015-04-15 06:13:14 +00:00
Rails is opinionated software. It makes the assumption that there is a "best"
2012-10-17 13:15:55 +00:00
way to do things, and it's designed to encourage that way - and in some cases to
discourage alternatives. If you learn "The Rails Way" you'll probably discover a
tremendous increase in productivity. If you persist in bringing old habits from
other languages to your Rails development, and trying to use patterns you
learned elsewhere, you may have a less happy experience.
The Rails philosophy includes two major guiding principles:
2014-02-25 12:20:15 +00:00
* **Don't Repeat Yourself:** DRY is a principle of software development which
2014-01-02 05:25:40 +00:00
states that "Every piece of knowledge must have a single, unambiguous, authoritative
2019-06-05 17:19:04 +00:00
representation within a system". By not writing the same information over and over
2014-01-02 05:25:40 +00:00
again, our code is more maintainable, more extensible, and less buggy.
* **Convention Over Configuration:** Rails has opinions about the best way to do many
things in a web application, and defaults to this set of conventions, rather than
2016-08-15 01:36:46 +00:00
require that you specify minutiae through endless configuration files.
2012-10-17 13:15:55 +00:00
Creating a New Rails Project
----------------------------
2020-10-28 21:08:51 +00:00
2015-07-24 09:27:36 +00:00
The best way to read this guide is to follow it step by step. All steps are
essential to run this example application and no additional code or steps are
needed.
2012-10-17 13:15:55 +00:00
By following along with this guide, you'll create a Rails project called
2014-06-14 14:18:22 +00:00
`blog` , a (very) simple weblog. Before you can start building the application,
2014-06-10 20:15:55 +00:00
you need to make sure that you have Rails itself installed.
2012-10-17 13:15:55 +00:00
2020-10-28 21:08:51 +00:00
NOTE: The examples below use `$` to represent your terminal prompt in a UNIX-like OS,
2014-01-02 05:25:40 +00:00
though it may have been customized to appear differently. If you are using Windows,
2020-10-28 21:08:51 +00:00
your prompt will look something like `C:\source_code>` .
2012-10-17 13:15:55 +00:00
### Installing Rails
2017-05-21 18:06:33 +00:00
Before you install Rails, you should check to make sure that your system has the
2020-02-17 11:30:39 +00:00
proper prerequisites installed. These include:
2020-03-05 23:30:47 +00:00
* Ruby
2020-02-17 11:30:39 +00:00
* SQLite3
* Node.js
* Yarn
#### Installing Ruby
2017-05-21 18:06:33 +00:00
2020-10-28 21:08:51 +00:00
Open up a command line prompt. On macOS open Terminal.app; on Windows choose
"Run" from your Start menu and type `cmd.exe` . Any commands prefaced with a
2012-12-05 02:09:06 +00:00
dollar sign `$` should be run in the command line. Verify that you have a
2012-11-29 12:10:03 +00:00
current version of Ruby installed:
2012-10-17 13:15:55 +00:00
2015-08-12 02:02:09 +00:00
```bash
2020-07-09 10:36:45 +00:00
$ ruby --version
2018-02-17 21:02:18 +00:00
ruby 2.5.0
2015-08-12 02:02:09 +00:00
```
2018-12-19 20:09:34 +00:00
Rails requires Ruby version 2.5.0 or later. If the version number returned is
2020-01-22 22:08:13 +00:00
less than that number (such as 2.3.7, or 1.8.7), you'll need to install a fresh copy of Ruby.
2017-05-21 18:06:33 +00:00
2020-03-05 23:30:47 +00:00
To install Rails on Windows, you'll first need to install [Ruby Installer ](https://rubyinstaller.org/ ).
2014-02-03 10:55:16 +00:00
2020-03-05 23:30:47 +00:00
For more installation methods for most Operating Systems take a look at
[ruby-lang.org ](https://www.ruby-lang.org/en/documentation/installation/ ).
2017-05-21 18:06:33 +00:00
2020-02-17 11:30:39 +00:00
#### Installing SQLite3
2017-05-21 18:06:33 +00:00
You will also need an installation of the SQLite3 database.
2014-12-10 15:34:21 +00:00
Many popular UNIX-like OSes ship with an acceptable version of SQLite3.
2020-03-05 23:30:47 +00:00
Others can find installation instructions at the [SQLite3 website ](https://www.sqlite.org ).
Verify that it is correctly installed and in your load `PATH` :
2014-01-02 05:25:40 +00:00
```bash
$ sqlite3 --version
```
The program should report its version.
2020-02-17 11:30:39 +00:00
#### Installing Node.js and Yarn
Finally, you'll need Node.js and Yarn installed to manage your application's JavaScript.
2020-03-05 23:30:47 +00:00
Find the installation instructions at the [Node.js website ](https://nodejs.org/en/download/ ) and
2020-02-17 11:30:39 +00:00
verify it's installed correctly with the following command:
2020-03-05 23:30:47 +00:00
```bash
2020-02-17 11:30:39 +00:00
$ node --version
```
The version of your Node.js runtime should be printed out. Make sure it's greater
than 8.16.0.
To install Yarn, follow the installation
instructions at the [Yarn website ](https://classic.yarnpkg.com/en/docs/install ).
Running this command should print out Yarn version:
```bash
2020-07-09 10:36:45 +00:00
$ yarn --version
2020-02-17 11:30:39 +00:00
```
If it says something like "1.22.0", Yarn has been installed correctly.
#### Installing Rails
2012-10-17 13:15:55 +00:00
To install Rails, use the `gem install` command provided by RubyGems:
```bash
$ gem install rails
```
2013-09-12 16:15:23 +00:00
To verify that you have everything installed correctly, you should be able to
run the following:
2012-10-17 13:15:55 +00:00
```bash
2014-07-22 13:49:32 +00:00
$ rails --version
2012-10-17 13:15:55 +00:00
```
2019-05-01 15:17:41 +00:00
If it says something like "Rails 6.0.0", you are ready to continue.
2012-10-17 13:15:55 +00:00
### Creating the Blog Application
2013-09-12 16:15:23 +00:00
Rails comes with a number of scripts called generators that are designed to make
your development life easier by creating everything that's necessary to start
working 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 that
you don't have to write it yourself.
2012-10-17 13:15:55 +00:00
2013-09-12 16:15:23 +00:00
To use this generator, open a terminal, navigate to a directory where you have
2020-10-28 21:08:51 +00:00
rights to create files, and run:
2012-10-17 13:15:55 +00:00
```bash
$ rails new blog
```
2014-01-13 22:10:22 +00:00
This will create a Rails application called Blog in a `blog` directory and
2013-09-12 16:15:23 +00:00
install the gem dependencies that are already mentioned in `Gemfile` using
`bundle install` .
2012-10-17 13:15:55 +00:00
2016-08-05 18:18:00 +00:00
NOTE: If you're using Windows Subsystem for Linux then there are currently some
limitations on file system notifications that mean you should disable the `spring`
2020-10-28 21:08:51 +00:00
and `listen` gems which you can do by running `rails new blog --skip-spring --skip-listen`
instead.
2016-08-05 18:18:00 +00:00
2013-09-12 16:15:23 +00:00
TIP: You can see all of the command line options that the Rails application
2020-10-28 21:08:51 +00:00
generator accepts by running `rails new --help` .
2012-10-17 13:15:55 +00:00
2014-01-13 22:10:22 +00:00
After you create the blog application, switch to its folder:
2012-10-17 13:15:55 +00:00
```bash
$ cd blog
```
2020-10-28 21:08:51 +00:00
The `blog` directory will have a number of generated files and folders that make
2014-01-13 22:10:22 +00:00
up the structure of a Rails application. Most of the work in this tutorial will
happen in the `app` folder, but here's a basic rundown on the function of each
2020-10-28 21:08:51 +00:00
of the files and folders that Rails creates by default:
2012-10-17 13:15:55 +00:00
| File/Folder | Purpose |
| ----------- | ------- |
2018-04-30 21:13:39 +00:00
|app/|Contains the controllers, models, views, helpers, mailers, channels, jobs, and assets for your application. You'll focus on this folder for the remainder of this guide.|
2020-10-28 21:08:51 +00:00
|bin/|Contains the `rails` script that starts your app and can contain other scripts you use to set up, update, deploy, or run your application.|
|config/|Contains configuration for your application's routes, database, and more. This is covered in more detail in [Configuring Rails Applications ](configuring.html ).|
|config.ru|Rack configuration for Rack-based servers used to start the application. For more information about Rack, see the [Rack website ](https://rack.github.io/ ).|
2014-02-10 22:55:37 +00:00
|db/|Contains your current database schema, as well as the database migrations.|
2017-08-23 00:36:38 +00:00
|Gemfile< br > 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 ](https://bundler.io ).|
2014-02-10 22:55:37 +00:00
|lib/|Extended modules for your application.|
|log/|Application log files.|
2017-09-13 16:26:04 +00:00
|package.json|This file allows you to specify what npm dependencies are needed for your Rails application. This file is used by Yarn. For more information about Yarn, see the [Yarn website ](https://yarnpkg.com/lang/en/ ).|
2020-10-28 21:08:51 +00:00
|public/|Contains static files and compiled assets. When your app is running, this directory will be exposed as-is.|
2017-10-06 06:02:56 +00:00
|Rakefile|This 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.|
2015-12-21 06:06:22 +00:00
|README.md|This 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.|
2018-04-30 21:28:11 +00:00
|storage/|Active Storage files for Disk Service. This is covered in [Active Storage Overview ](active_storage_overview.html ).|
2014-02-10 22:55:37 +00:00
|test/|Unit tests, fixtures, and other test apparatus. These are covered in [Testing Rails Applications ](testing.html ).|
2015-01-03 18:20:54 +00:00
|tmp/|Temporary files (like cache and pid files).|
2014-02-10 22:55:37 +00:00
|vendor/|A place for all third-party code. In a typical Rails application this includes vendored gems.|
2020-10-28 21:08:51 +00:00
|.gitignore|This file tells git which files (or patterns) it should ignore. See [GitHub - Ignoring files ](https://help.github.com/articles/ignoring-files ) for more info about ignoring files.|
2017-09-13 16:26:04 +00:00
|.ruby-version|This file contains the default Ruby version.|
2012-10-17 13:15:55 +00:00
Hello, Rails!
-------------
2013-09-12 16:15:23 +00:00
To begin with, let's get some text up on screen quickly. To do this, you need to
get your Rails application server running.
2012-10-17 13:15:55 +00:00
### Starting up the Web Server
2013-09-12 16:15:23 +00:00
You actually have a functional Rails application already. To see it, you need to
start a web server on your development machine. You can do this by running the
2020-10-28 21:08:51 +00:00
following command in the `blog` directory:
2012-10-17 13:15:55 +00:00
```bash
2019-01-22 08:53:47 +00:00
$ bin/rails server
2012-10-17 13:15:55 +00:00
```
2015-01-25 11:16:32 +00:00
TIP: If you are using Windows, you have to pass the scripts under the `bin`
2015-01-25 06:02:54 +00:00
folder directly to the Ruby interpreter e.g. `ruby bin\rails server` .
2019-05-01 21:22:10 +00:00
TIP: JavaScript asset compression requires you
2014-08-03 04:43:38 +00:00
have a JavaScript runtime available on your system, in the absence
2019-05-01 22:12:46 +00:00
of a runtime you will see an `execjs` error during asset compression.
2017-02-20 13:44:39 +00:00
Usually macOS and Windows come with a JavaScript runtime installed.
2014-08-03 04:43:38 +00:00
`therubyrhino` is the recommended runtime for JRuby users and is added by
default to the `Gemfile` in apps generated under JRuby. You can investigate
2015-03-12 22:22:10 +00:00
all the supported runtimes at [ExecJS ](https://github.com/rails/execjs#readme ).
2012-10-17 13:15:55 +00:00
2020-10-28 21:08:51 +00:00
This will start up Puma, a web server distributed with Rails by default. To see
2014-01-13 22:10:22 +00:00
your application in action, open a browser window and navigate to
< http: / / localhost:3000 > . You should see the Rails default information page:
2012-10-17 13:15:55 +00:00
2019-10-19 02:38:42 +00:00
![Yay! You're on Rails! screenshot ](images/getting_started/rails_welcome.png )
2012-10-17 13:15:55 +00:00
2020-10-28 21:08:51 +00:00
When you want to stop the web server, hit Ctrl+C in the terminal window where
it's running. In the development environment, Rails does not generally
2020-09-30 21:51:15 +00:00
require you to restart the server; changes you make in files will be
automatically picked up by the server.
2012-10-17 13:15:55 +00:00
2019-10-19 02:38:42 +00:00
The "Yay! You're on Rails!" page is the _smoke test_ for a new Rails
application: it makes sure that you have your software configured correctly
enough to serve a page.
2012-10-17 13:15:55 +00:00
### Say "Hello", Rails
2020-10-28 21:19:02 +00:00
To get Rails saying "Hello", you need to create at minimum a *route* , a
*controller* with an *action* , and a *view* . A route maps a request to a
controller action. A controller action performs the necessary work to handle the
request, and prepares any data for the view. A view displays data in a desired
format.
2012-10-17 13:15:55 +00:00
2020-10-28 21:19:02 +00:00
In terms of implementation: Routes are rules written in a Ruby [DSL
(Domain-Specific Language)](https://en.wikipedia.org/wiki/Domain-specific_language).
Controllers are Ruby classes, and their public methods are actions. And views
are templates, usually written in a mixture of HTML and Ruby.
2012-10-17 13:15:55 +00:00
2020-10-28 21:19:02 +00:00
Let's start by adding a route to our routes file, `config/routes.rb` , at the
top of the `Rails.application.routes.draw` block:
2020-01-22 22:08:13 +00:00
```ruby
Rails.application.routes.draw do
get "/articles", to: "articles#index"
# For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
end
```
2020-10-28 21:19:02 +00:00
The route above declares that `GET /articles` requests are mapped to the `index`
action of `ArticlesController` .
2020-01-22 22:08:13 +00:00
2020-10-28 21:19:02 +00:00
To create `ArticlesController` and its `index` action, we'll run the controller
generator (with the `--skip-routes` option because we already have an
appropriate route):
2012-10-17 13:15:55 +00:00
```bash
2020-10-28 21:19:02 +00:00
$ bin/rails generate controller Articles index --skip-routes
2012-10-17 13:15:55 +00:00
```
2020-10-28 21:19:02 +00:00
Rails will create several files for you:
2012-10-17 13:15:55 +00:00
2020-06-13 23:07:03 +00:00
```
2020-01-22 22:08:13 +00:00
create app/controllers/articles_controller.rb
2012-10-17 13:15:55 +00:00
invoke erb
2020-01-22 22:08:13 +00:00
create app/views/articles
create app/views/articles/index.html.erb
2012-10-17 13:15:55 +00:00
invoke test_unit
2020-01-22 22:08:13 +00:00
create test/controllers/articles_controller_test.rb
2012-10-17 13:15:55 +00:00
invoke helper
2020-01-22 22:08:13 +00:00
create app/helpers/articles_helper.rb
2016-05-11 14:49:00 +00:00
invoke test_unit
2012-10-17 13:15:55 +00:00
invoke assets
invoke scss
2020-01-22 22:08:13 +00:00
create app/assets/stylesheets/articles.scss
2012-10-17 13:15:55 +00:00
```
2020-10-28 21:19:02 +00:00
The most important of these is the controller file,
`app/controllers/articles_controller.rb` . Let's take a look at it:
2020-01-22 22:08:13 +00:00
```ruby
class ArticlesController < ApplicationController
def index
end
end
```
2020-10-28 21:19:02 +00:00
The `index` action is empty. When an action does not explicitly render a view
(or otherwise trigger an HTTP response), Rails will automatically render a view
that matches the name of the controller and action. Convention Over
Configuration! Views are located in the `app/views` directory. So the `index`
action will render `app/views/articles/index.html.erb` by default.
2020-01-22 22:08:13 +00:00
2020-10-28 21:19:02 +00:00
Let's open `app/views/articles/index.html.erb` , and replace its contents with:
2012-10-17 13:15:55 +00:00
```html
< h1 > Hello, Rails!< / h1 >
```
2020-10-28 21:19:02 +00:00
If you previously stopped the web server to run the controller generator,
restart it with `bin/rails server` . Now visit < http: // localhost:3000 / articles > ,
and see our text displayed!
2020-01-22 22:08:13 +00:00
2012-10-17 13:15:55 +00:00
### Setting the Application Home Page
2020-10-28 21:24:21 +00:00
At the moment, < http: / / localhost:3000 > still displays "Yay! You're on Rails!".
Let's display our "Hello, Rails!" text at < http: / / localhost:3000 > as well. To do
so, we will add a route that maps the *root path* of our application to the
appropriate controller and action.
2012-10-17 13:15:55 +00:00
2020-10-28 21:24:21 +00:00
Let's open `config/routes.rb` , and add the following `root` route to the top of
the `Rails.application.routes.draw` block:
2012-10-17 13:15:55 +00:00
```ruby
2014-01-13 22:10:22 +00:00
Rails.application.routes.draw do
2020-10-28 21:24:21 +00:00
root "articles#index"
2012-10-17 13:15:55 +00:00
2020-10-28 21:24:21 +00:00
get "/articles", to: "articles#index"
2016-02-25 16:20:15 +00:00
end
2012-10-17 13:15:55 +00:00
```
2020-10-28 21:24:21 +00:00
Now we can see our "Hello, Rails!" text when we visit < http: / / localhost:3000 > ,
confirming that the `root` route is also mapped to the `index` action of
`ArticlesController` .
2012-10-17 13:15:55 +00:00
2020-10-28 21:24:21 +00:00
TIP: To learn more about routing, see [Rails Routing from the Outside In](
routing.html).
2012-10-17 13:15:55 +00:00
2020-10-28 21:32:44 +00:00
MVC and You
-----------
So far, we've discussed routes, controllers, actions, and views. All of these
are typical pieces of a web application that follows the [MVC (Model-View-Controller)](
https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller) pattern.
MVC is a design pattern that divides the responsibilities of an application to
make it easier to reason about. Rails follows this design pattern by convention.
Since we have a controller and a view to work with, let's generate the next
piece: a model.
2020-10-28 21:34:09 +00:00
### Generating a Model
A *model* is a Ruby class that is used to represent data. Additionally, models
can interact with the application's database through a feature of Rails called
*Active Record*.
To define a model, we will use the model generator:
```bash
$ bin/rails generate model Article title:string body:text
```
NOTE: Model names are **singular** , because an instantiated model represents a
single data record. To help remember this convention, think of how you would
call the model's constructor: we want to write `Article.new(...)` , **not**
`Articles.new(...)` .
This will create several files:
```
invoke active_record
create db/migrate/< timestamp > _create_articles.rb
create app/models/article.rb
invoke test_unit
create test/models/article_test.rb
create test/fixtures/articles.yml
```
The two files we'll focus on are the migration file
(`db/migrate/< timestamp > _create_articles.rb`) and the model file
(`app/models/article.rb`).
2020-10-28 21:36:19 +00:00
### Database Migrations
*Migrations* are used to alter the structure of an application's database. In
Rails applications, migrations are written in Ruby so that they can be
database-agnostic.
Let's take a look at the contents of our new migration file:
```ruby
class CreateArticles < ActiveRecord::Migration [ 6 . 0 ]
def change
create_table :articles do |t|
t.string :title
t.text :body
t.timestamps
end
end
end
```
The call to `create_table` specifies how the `articles` table should be
constructed. By default, the `create_table` method adds an `id` column as an
auto-incrementing primary key. So the first record in the table will have an
`id` of 1, the next record will have an `id` of 2, and so on.
Inside the block for `create_table` , two columns are defined: `title` and
`body` . These were added by the generator because we included them in our
generate command (`bin/rails generate model Article title:string body:text`).
On the last line of the block is a call to `t.timestamps` . This method defines
two additional columns named `created_at` and `updated_at` . As we will see,
Rails will manage these for us, setting the values when we create or update a
model object.
Let's run our migration with the following command:
```bash
$ bin/rails db:migrate
```
The command will display output indicating that the table was created:
```
== CreateArticles: migrating ===================================
-- create_table(:articles)
-> 0.0018s
== CreateArticles: migrated (0.0018s) ==========================
```
TIP: To learn more about migrations, see [Active Record Migrations](
active_record_migrations.html).
Now we can interact with the table using our model.
2020-10-28 21:39:31 +00:00
### Using a Model to Interact with the Database
To play with our model a bit, we're going to use a feature of Rails called the
*console*. The console is an interactive coding environment just like `irb` , but
it also automatically loads Rails and our application code.
Let's launch the console with this command:
```bash
$ bin/rails console
```
You should see an `irb` prompt like:
```irb
Loading development environment (Rails 6.0.2.1)
irb(main):001:0>
```
At this prompt, we can initialize a new `Article` object:
```irb
irb> article = Article.new(title: "Hello Rails", body: "I am on Rails!")
```
It's important to note that we have only *initialized* this object. This object
is not saved to the database at all. It's only available in the console at the
moment. To save the object to the database, we must call [`save`](
https://api.rubyonrails.org/classes/ActiveRecord/Persistence.html#method-i-save):
```irb
irb> article.save
(0.1ms) begin transaction
Article Create (0.4ms) INSERT INTO "articles" ("title", "body", "created_at", "updated_at") VALUES (?, ?, ?, ?) [["title", "Hello Rails"], ["body", "I am on Rails!"], ["created_at", "2020-01-18 23:47:30.734416"], ["updated_at", "2020-01-18 23:47:30.734416"]]
(0.9ms) commit transaction
=> true
```
The above output shows an `INSERT INTO "articles" ...` database query. This
indicates that the article has been inserted into our table. And if we take a
look at the `article` object again, we see something interesting has happened:
```irb
irb> article
=> #< Article id: 1 , title: " Hello Rails " , body: " I am on Rails ! " , created_at: " 2020-01-18 23:47:30 " , updated_at: " 2020-01-18 23:47:30 " >
```
The `id` , `created_at` , and `updated_at` attributes of the object are now set.
Rails did this for us when we saved the object.
When we want to fetch this article from the database, we can call [`find`](
https://api.rubyonrails.org/classes/ActiveRecord/FinderMethods.html#method-i-find)
on the model and pass the `id` as an argument:
```irb
irb> Article.find(1)
=> #< Article id: 1 , title: " Hello Rails " , body: " I am on Rails ! " , created_at: " 2020-01-18 23:47:30 " , updated_at: " 2020-01-18 23:47:30 " >
```
And when we want to fetch all articles from the database, we can call [`all`](
https://api.rubyonrails.org/classes/ActiveRecord/Scoping/Named/ClassMethods.html#method-i-all)
on the model:
```irb
irb> Article.all
=> #< ActiveRecord::Relation [ # < Article id: 1 , title: " Hello Rails " , body: " I am on Rails ! " , created_at: " 2020-01-18 23:47:30 " , updated_at: " 2020-01-18 23:47:30 " > ]>
```
This method returns an [`ActiveRecord::Relation`](
https://api.rubyonrails.org/classes/ActiveRecord/Relation.html) object, which
you can think of as a super-powered array.
TIP: To learn more about models, see [Active Record Basics](
active_record_basics.html) and [Active Record Query Interface](
active_record_querying.html).
Models are the final piece of the MVC puzzle. Next, we will connect all of the
pieces together.
2020-10-28 21:42:21 +00:00
### Showing a List of Articles
Let's go back to our controller in `app/controllers/articles_controller.rb` , and
change the `index` action to fetch all articles from the database:
```ruby
class ArticlesController < ApplicationController
def index
@articles = Article.all
end
end
```
Controller instance variables can be accessed by the view. That means we can
reference `@articles` in `app/views/articles/index.html.erb` . Let's open that
file, and replace its contents with:
```html+erb
< h1 > Articles< / h1 >
< ul >
< % @articles .each do |article| %>
< li >
< %= article.title %>
< / li >
< % end %>
< / ul >
```
The above code is a mixture of HTML and *ERB* . ERB is a templating system that
evaluates Ruby code embedded in a document. Here, we can see two types of ERB
tags: `<% %>` and `<%= %>` . The `<% %>` tag means "evaluate the enclosed Ruby
code." The `<%= %>` tag means "evaluate the enclosed Ruby code, and output the
value it returns." Anything you could write in a regular Ruby program can go
inside these ERB tags, though it's usually best to keep the contents of ERB tags
short, for readability.
Since we don't want to output the value returned by `@articles.each` , we've
enclosed that code in `<% %>` . But, since we *do* want to output the value
returned by `article.title` (for each article), we've enclosed that code in
`<%= %>` .
We can see the final result by visiting < http: / / localhost:3000 > . (Remember that
`bin/rails server` must be running!) Here's what happens when we do that:
1. The browser makes a request: `GET http://localhost:3000` .
2. Our Rails application receives this request.
3. The Rails router maps the root route to the `index` action of `ArticlesController` .
4. The `index` action uses the `Article` model to fetch all articles in the database.
5. Rails automatically renders the `app/views/articles/index.html.erb` view.
6. The ERB code in the view is evaluated to output HTML.
7. The server sends a response containing the HTML back to the browser.
We've connected all the MVC pieces together, and we have our first controller
action! Next, we'll move on to the second action.
2020-10-28 21:43:40 +00:00
CRUDit Where CRUDit Is Due
--------------------------
2012-10-17 13:15:55 +00:00
2020-10-28 21:43:40 +00:00
Almost all web applications involve [CRUD (Create, Read, Update, and Delete)](
https://en.wikipedia.org/wiki/Create,_read,_update,_and_delete) operations. You
may even find that the majority of the work your application does is CRUD. Rails
acknowledges this, and provides many features to help simplify code doing CRUD.
Let's begin exploring these features by adding more functionality to our
application.
2012-10-17 13:15:55 +00:00
2020-10-28 21:45:26 +00:00
### Showing a Single Article
We currently have a view that lists all articles in our database. Let's add a
new view that shows the title and body of a single article.
We start by adding a new route that maps to a new controller action (which we
will add next). Open `config/routes.rb` , and insert the last route shown here:
```ruby
Rails.application.routes.draw do
root "articles#index"
get "/articles", to: "articles#index"
get "/articles/:id", to: "articles#show"
end
```
The new route is another `get` route, but it has something extra in its path:
`:id` . This designates a route *parameter* . A route parameter captures a segment
of the request's path, and puts that value into the `params` Hash, which is
accessible by the controller action. For example, when handling a request like
`GET http://localhost:3000/articles/1` , `1` would be captured as the value for
`:id` , which would then be accessible as `params[:id]` in the `show` action of
`ArticlesController` .
Let's add that `show` action now, below the `index` action in
`app/controllers/articles_controller.rb` :
```ruby
class ArticlesController < ApplicationController
def index
@articles = Article.all
end
def show
@article = Article.find(params[:id])
end
end
```
The `show` action calls `Article.find` ([mentioned
previously](#using-a-model-to-interact-with-the-database)) with the ID captured
by the route parameter. The returned article is stored in the `@article`
instance variable, so it is accessible by the view. By default, the `show`
action will render `app/views/articles/show.html.erb` .
Let's create `app/views/articles/show.html.erb` , with the following contents:
```html+erb
< h1 > < %= @article .title %></ h1 >
< p > < %= @article .body %></ p >
```
Now we can see the article when we visit < http: / / localhost:3000 / articles / 1 > !
To finish up, let's add a convenient way to get to an article's page. We'll link
each article's title in `app/views/articles/index.html.erb` to its page:
```html+erb
< h1 > Articles< / h1 >
< ul >
< % @articles .each do |article| %>
< li >
< a href = "/articles/<%= article.id %>" >
< %= article.title %>
< / a >
< / li >
< % end %>
< / ul >
```
2020-10-28 21:54:45 +00:00
### Resourceful Routing
2012-10-17 13:15:55 +00:00
2020-10-28 21:54:45 +00:00
So far, we've covered the "R" (Read) of CRUD. We will eventually cover the "C"
(Create), "U" (Update), and "D" (Delete). As you might have guessed, we will do
so by adding new routes, controller actions, and views. Whenever we have such a
combination of routes, controller actions, and views that work together to
perform CRUD operations on an entity, we call that entity a *resource* . For
example, in our application, we would say an article is a resource.
Rails provides a routes method named [`resources`](
https://api.rubyonrails.org/classes/ActionDispatch/Routing/Mapper/Resources.html#method-i-resources)
that maps all of the conventional routes for a collection of resources, such as
articles. So before we proceed to the "C", "U", and "D" sections, let's replace
the two `get` routes in `config/routes.rb` with `resources` :
2012-10-17 13:15:55 +00:00
2013-04-23 06:31:16 +00:00
```ruby
2014-04-12 13:31:00 +00:00
Rails.application.routes.draw do
2020-10-28 21:54:45 +00:00
root "articles#index"
2012-10-17 13:15:55 +00:00
2014-01-20 19:06:44 +00:00
resources :articles
2013-04-23 06:31:16 +00:00
end
```
2012-10-17 13:15:55 +00:00
2020-10-28 21:54:45 +00:00
We can inspect what routes are mapped by running the `bin/rails routes` command:
2012-10-17 13:15:55 +00:00
2013-04-23 06:31:16 +00:00
```bash
2019-01-22 08:53:47 +00:00
$ bin/rails routes
2020-10-28 21:54:45 +00:00
Prefix Verb URI Pattern Controller#Action
root GET / articles#index
articles GET /articles(.:format) articles#index
new_article GET /articles/new(.:format) articles#new
article GET /articles/:id(.:format) articles#show
POST /articles(.:format) articles#create
edit_article GET /articles/:id/edit(.:format) articles#edit
PATCH /articles/:id(.:format) articles#update
DELETE /articles/:id(.:format) articles#destroy
```
The `resources` method also sets up URL and path helper methods that we can use
to keep our code from depending on a specific route configuration. The values
in the "Prefix" column above plus a suffix of `_url` or `_path` form the names
of these helpers. For example, the `article_path` helper returns
`"/articles/#{article.id}"` when given an article. We can use it to tidy up our
links in `app/views/articles/index.html.erb` :
```html+erb
< h1 > Articles< / h1 >
< ul >
< % @articles .each do |article| %>
< li >
< a href = "<%= article_path(article) %>" >
< %= article.title %>
< / a >
< / li >
< % end %>
< / ul >
```
However, we will take this one step further by using the [`link_to`](
https://api.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html#method-i-link_to)
helper. The `link_to` helper renders a link with its first argument as the
link's text and its second argument as the link's destination. If we pass a
model object as the second argument, `link_to` will call the appropriate path
helper to convert the object to a path. For example, if we pass an article,
`link_to` will call `article_path` . So `app/views/articles/index.html.erb`
becomes:
```html+erb
< h1 > Articles< / h1 >
< ul >
< % @articles .each do |article| %>
< li >
< %= link_to article.title, article %>
< / li >
< % end %>
< / ul >
```
Nice!
TIP: To learn more about routing, see [Rails Routing from the Outside In](
routing.html).
2012-10-17 13:15:55 +00:00
2020-10-28 21:56:01 +00:00
### Creating a New Article
2012-10-17 13:15:55 +00:00
2020-10-28 21:56:01 +00:00
Now we move on to the "C" (Create) of CRUD. Typically, in web applications,
creating a new resource is a multi-step process. First, the user requests a form
to fill out. Then, the user submits the form. If there are no errors, then the
resource is created and some kind of confirmation is displayed. Else, the form
is redisplayed with error messages, and the process is repeated.
2012-10-17 13:15:55 +00:00
2020-10-28 21:56:01 +00:00
In a Rails application, these steps are conventionally handled by a controller's
`new` and `create` actions. Let's add a typical implementation of these actions
to `app/controllers/articles_controller.rb` , below the `show` action:
2012-10-17 13:15:55 +00:00
```ruby
2014-01-20 19:06:44 +00:00
class ArticlesController < ApplicationController
2020-10-28 21:56:01 +00:00
def index
@articles = Article.all
end
2012-10-17 13:15:55 +00:00
2020-10-28 21:56:01 +00:00
def show
@article = Article.find(params[:id])
end
2012-10-17 13:15:55 +00:00
2020-10-28 21:56:01 +00:00
def new
@article = Article.new
end
2012-10-17 13:15:55 +00:00
2020-10-28 21:56:01 +00:00
def create
@article = Article.new(title: "...", body: "...")
2012-10-17 13:15:55 +00:00
2020-10-28 21:56:01 +00:00
if @article .save
redirect_to @article
else
render :new
end
2014-04-29 14:56:43 +00:00
end
2012-10-17 13:15:55 +00:00
end
```
2020-10-28 21:56:01 +00:00
The `new` action instantiates a new article, but does not save it. This article
will be used in the view when building the form. By default, the `new` action
will render `app/views/articles/new.html.erb` , which we will create next.
2014-12-15 01:05:51 +00:00
2020-10-28 21:56:01 +00:00
The `create` action instantiates a new article with values for the title and
body, and attempts to save it. If the article is saved successfully, the action
redirects the browser to the article's page at `"http://localhost:3000/articles/#{@article.id}"` .
Else, the action redisplays the form by rendering `app/views/articles/new.html.erb` .
The title and body here are dummy values. After we create the form, we will come
back and change these.
2013-09-12 16:15:23 +00:00
2020-10-28 21:56:01 +00:00
NOTE: [`redirect_to` ](https://api.rubyonrails.org/classes/ActionController/Redirecting.html#method-i-redirect_to )
will cause the browser to make a new request,
whereas [`render` ](https://api.rubyonrails.org/classes/AbstractController/Rendering.html#method-i-render )
renders the specified view for the current request.
It is important to use `redirect_to` after mutating the database or application state.
Otherwise, if the user refreshes the page, the browser will make the same request, and the mutation will be repeated.
2012-10-17 13:15:55 +00:00
2020-10-28 21:57:45 +00:00
#### Using a Form Builder
2012-10-17 13:15:55 +00:00
2020-10-28 21:57:45 +00:00
We will use a feature of Rails called a *form builder* to create our form. Using
a form builder, we can write a minimal amount of code to output a form that is
fully configured and follows Rails conventions.
Let's create `app/views/articles/new.html.erb` with the following contents:
2012-10-17 13:15:55 +00:00
```html+erb
2020-10-28 21:57:45 +00:00
< h1 > New Article< / h1 >
2020-11-29 10:48:16 +00:00
< %= form_with model: @article do |form| %>
2020-10-28 21:57:45 +00:00
< div >
2017-04-27 20:30:40 +00:00
< %= form.label :title %>< br >
< %= form.text_field :title %>
2020-10-28 21:57:45 +00:00
< / div >
2012-10-17 13:15:55 +00:00
2020-10-28 21:57:45 +00:00
< div >
< %= form.label :body %>< br >
< %= form.text_area :body %>
< / div >
2012-10-17 13:15:55 +00:00
2020-10-28 21:57:45 +00:00
< div >
2017-04-27 20:30:40 +00:00
< %= form.submit %>
2020-10-28 21:57:45 +00:00
< / div >
2012-10-17 13:15:55 +00:00
< % end %>
```
2020-10-28 21:57:45 +00:00
The [`form_with` ](https://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html#method-i-form_with )
helper method instantiates a form builder. In the `form_with` block we call
methods like [`label` ](https://api.rubyonrails.org/classes/ActionView/Helpers/FormBuilder.html#method-i-label )
and [`text_field` ](https://api.rubyonrails.org/classes/ActionView/Helpers/FormBuilder.html#method-i-text_field )
on the form builder to output the appropriate form elements.
2012-10-17 13:15:55 +00:00
2020-10-28 21:57:45 +00:00
The resulting output from our `form_with` call will look like:
2012-10-17 13:15:55 +00:00
2020-10-28 21:57:45 +00:00
```html
< form action = "/articles" accept-charset = "UTF-8" method = "post" >
< input type = "hidden" name = "authenticity_token" value = "..." >
2012-10-17 13:15:55 +00:00
2020-10-28 21:57:45 +00:00
< div >
< label for = "article_title" > Title< / label > < br >
< input type = "text" name = "article[title]" id = "article_title" >
< / div >
2012-10-17 13:15:55 +00:00
2020-10-28 21:57:45 +00:00
< div >
< label for = "article_body" > Body< / label > < br >
< textarea name = "article[body]" id = "article_body" > < / textarea >
< / div >
2012-10-17 13:15:55 +00:00
2020-10-28 21:57:45 +00:00
< div >
< input type = "submit" name = "commit" value = "Create Article" data-disable-with = "Create Article" >
< / div >
< / form >
```
2013-09-27 15:45:15 +00:00
2020-10-28 21:57:45 +00:00
TIP: To learn more about form builders, see [Action View Form Helpers](
form_helpers.html).
2017-04-27 20:30:40 +00:00
2020-10-28 21:58:46 +00:00
#### Using Strong Parameters
Submitted form data is put into the `params` Hash, alongside captured route
parameters. Thus, the `create` action can access the submitted title via
`params[:article][:title]` and the submitted body via `params[:article][:body]` .
We could pass these values individually to `Article.new` , but that would be
verbose and possibly error-prone. And it would become worse as we add more
fields.
Instead, we will pass a single Hash that contains the values. However, we must
still specify what values are allowed in that Hash. Otherwise, a malicious user
could potentially submit extra form fields and overwrite private data. In fact,
if we pass the unfiltered `params[:article]` Hash directly to `Article.new` ,
Rails will raise a `ForbiddenAttributesError` to alert us about the problem.
So we will use a feature of Rails called *Strong Parameters* to filter `params` .
Think of it as [strong typing ](https://en.wikipedia.org/wiki/Strong_and_weak_typing )
for `params` .
Let's add a private method to the bottom of `app/controllers/articles_controller.rb`
named `article_params` that filters `params` . And let's change `create` to use
it:
2012-10-17 13:15:55 +00:00
```ruby
2020-10-28 21:58:46 +00:00
class ArticlesController < ApplicationController
def index
@articles = Article.all
end
2014-05-03 17:40:24 +00:00
2020-10-28 21:58:46 +00:00
def show
@article = Article.find(params[:id])
end
2014-03-15 23:28:34 +00:00
2020-10-28 21:58:46 +00:00
def new
@article = Article.new
end
2014-03-15 23:28:34 +00:00
2020-10-28 21:58:46 +00:00
def create
@article = Article.new(article_params)
2013-08-08 10:53:30 +00:00
2020-10-28 21:58:46 +00:00
if @article .save
redirect_to @article
else
render :new
end
end
2013-08-08 10:53:30 +00:00
2020-10-28 21:58:46 +00:00
private
def article_params
params.require(:article).permit(:title, :body)
end
2013-08-08 10:53:30 +00:00
end
```
2020-10-28 21:58:46 +00:00
TIP: To learn more about Strong Parameters, see [Action Controller Overview §
Strong Parameters](action_controller_overview.html#strong-parameters).
2013-08-08 10:53:30 +00:00
2020-10-28 22:00:37 +00:00
#### Validations and Displaying Error Messages
2012-10-17 13:15:55 +00:00
2020-10-28 22:00:37 +00:00
As we have seen, creating a resource is a multi-step process. Handling invalid
user input is another step of that process. Rails provides a feature called
*validations* to help us deal with invalid user input. Validations are rules
that are checked before a model object is saved. If any of the checks fail, the
save will be aborted, and appropriate error messages will be added to the
`errors` attribute of the model object.
2012-10-17 13:15:55 +00:00
2020-10-28 22:00:37 +00:00
Let's add some validations to our model in `app/models/article.rb` :
2012-10-17 13:15:55 +00:00
```ruby
2015-12-17 10:30:30 +00:00
class Article < ApplicationRecord
2020-10-28 22:00:37 +00:00
validates :title, presence: true
validates :body, presence: true, length: { minimum: 10 }
2012-10-17 13:15:55 +00:00
end
```
2020-10-28 22:00:37 +00:00
The first validation declares that a `title` value must be present. Because
`title` is a string, this means that the `title` value must contain at least one
non-whitespace character.
2012-10-17 13:15:55 +00:00
2020-10-28 22:00:37 +00:00
The second validation declares that a `body` value must also be present.
Additionally, it declares that the `body` value must be at least 10 characters
long.
2012-10-17 13:15:55 +00:00
2020-10-28 22:00:37 +00:00
NOTE: You may be wondering where the `title` and `body` attributes are defined.
Active Record automatically defines model attributes for every table column, so
you don't have to declare those attributes in your model file.
2012-10-17 13:15:55 +00:00
2020-10-28 22:00:37 +00:00
With our validations in place, let's modify `app/views/articles/new.html.erb` to
display any error messages for `title` and `body` :
2012-10-17 13:15:55 +00:00
```html+erb
2020-10-28 22:00:37 +00:00
< h1 > New Article< / h1 >
2014-04-20 15:26:51 +00:00
2020-11-29 10:48:16 +00:00
< %= form_with model: @article do |form| %>
2020-10-28 22:00:37 +00:00
< div >
2017-04-27 20:30:40 +00:00
< %= form.label :title %>< br >
< %= form.text_field :title %>
2020-12-20 00:06:54 +00:00
< % @article .errors.full_messages_for(:title).each do |message| %>
2020-10-28 22:00:37 +00:00
< div > < %= message %>< / div >
< % end %>
< / div >
2012-10-17 13:15:55 +00:00
2020-10-28 22:00:37 +00:00
< div >
< %= form.label :body %>< br >
< %= form.text_area :body %>< br >
2020-12-20 00:06:54 +00:00
< % @article .errors.full_messages_for(:body).each do |message| %>
2020-10-28 22:00:37 +00:00
< div > < %= message %>< / div >
< % end %>
< / div >
2012-10-17 13:15:55 +00:00
2020-10-28 22:00:37 +00:00
< div >
2017-04-27 20:30:40 +00:00
< %= form.submit %>
2020-10-28 22:00:37 +00:00
< / div >
2012-10-17 13:15:55 +00:00
< % end %>
```
2020-10-28 22:00:37 +00:00
The [`full_messages_for` ](https://api.rubyonrails.org/classes/ActiveModel/Errors.html#method-i-full_messages_for )
method returns an array of user-friendly error messages for a specified
attribute. If there are no errors for that attribute, the array will be empty.
2012-10-17 13:15:55 +00:00
2020-10-28 22:00:37 +00:00
To understand how all of this works together, let's take another look at the
`new` and `create` controller actions:
2012-10-17 13:15:55 +00:00
2020-10-28 22:00:37 +00:00
```ruby
def new
@article = Article.new
end
2012-10-17 13:15:55 +00:00
2020-10-28 22:00:37 +00:00
def create
@article = Article.new(article_params)
2012-10-17 13:15:55 +00:00
2020-10-28 22:00:37 +00:00
if @article .save
redirect_to @article
else
render :new
end
end
```
2012-10-17 13:15:55 +00:00
2020-10-28 22:00:37 +00:00
When we visit < http: // localhost:3000 / articles / new > , the `GET /articles/new`
request is mapped to the `new` action. The `new` action does not attempt to save
`@article` . Therefore, validations are not checked, and there will be no error
messages.
When we submit the form, the `POST /articles` request is mapped to the `create`
action. The `create` action *does* attempt to save `@article` . Therefore,
validations *are* checked. If any validation fails, `@article` will not be
saved, and `app/views/articles/new.html.erb` will be rendered with error
messages.
TIP: To learn more about validations, see [Active Record Validations](
active_record_validations.html). To learn more about validation error messages,
see [Active Record Validations § Working with Validation Errors](
active_record_validations.html#working-with-validation-errors).
2012-10-17 13:15:55 +00:00
2020-10-28 22:01:45 +00:00
#### Finishing Up
We can now create an article by visiting < http: / / localhost:3000 / articles / new > .
To finish up, let's link to that page from the bottom of
`app/views/articles/index.html.erb` :
```html+erb
< h1 > Articles< / h1 >
< ul >
< % @articles .each do |article| %>
< li >
< %= link_to article.title, article %>
< / li >
< % end %>
< / ul >
< %= link_to "New Article", new_article_path %>
```
2020-10-28 22:03:17 +00:00
### Updating an Article
2012-10-17 13:15:55 +00:00
2020-10-28 22:03:17 +00:00
We've covered the "CR" of CRUD. Now let's move on to the "U" (Update). Updating
a resource is very similar to creating a resource. They are both multi-step
processes. First, the user requests a form to edit the data. Then, the user
submits the form. If there are no errors, then the resource is updated. Else,
the form is redisplayed with error messages, and the process is repeated.
2012-10-17 13:15:55 +00:00
2020-10-28 22:03:17 +00:00
These steps are conventionally handled by a controller's `edit` and `update`
actions. Let's add a typical implementation of these actions to
`app/controllers/articles_controller.rb` , below the `create` action:
2012-10-17 13:15:55 +00:00
```ruby
2020-10-28 22:03:17 +00:00
class ArticlesController < ApplicationController
def index
@articles = Article.all
2014-04-29 14:56:43 +00:00
end
2019-12-08 00:25:49 +00:00
2020-10-28 22:03:17 +00:00
def show
@article = Article.find(params[:id])
end
2014-04-29 14:56:43 +00:00
2020-10-28 22:03:17 +00:00
def new
@article = Article.new
2014-04-29 14:56:43 +00:00
end
2020-10-28 22:03:17 +00:00
def create
@article = Article.new(article_params)
2012-10-17 13:15:55 +00:00
2020-10-28 22:03:17 +00:00
if @article .save
redirect_to @article
else
render :new
end
2012-10-17 13:15:55 +00:00
end
2013-06-29 20:03:27 +00:00
2020-10-28 22:03:17 +00:00
def edit
@article = Article.find(params[:id])
2013-06-29 20:03:27 +00:00
end
2020-10-28 22:03:17 +00:00
def update
@article = Article.find(params[:id])
2012-10-17 13:15:55 +00:00
2020-10-28 22:03:17 +00:00
if @article .update(article_params)
redirect_to @article
else
render :edit
end
end
2012-10-17 13:15:55 +00:00
2020-10-28 22:03:17 +00:00
private
def article_params
params.require(:article).permit(:title, :body)
end
end
2012-10-17 13:15:55 +00:00
```
2020-10-28 22:03:17 +00:00
Notice how the `edit` and `update` actions resemble the `new` and `create`
actions.
2012-10-17 13:15:55 +00:00
2020-10-28 22:03:17 +00:00
The `edit` action fetches the article from the database, and stores it in
`@article` so that it can be used when building the form. By default, the `edit`
action will render `app/views/articles/edit.html.erb` .
2012-10-17 13:15:55 +00:00
2020-10-28 22:03:17 +00:00
The `update` action (re-)fetches the article from the database, and attempts
to update it with the submitted form data filtered by `article_params` . If no
validations fail and the update is successful, the action redirects the browser
to the article's page. Else, the action redisplays the form, with error
messages, by rendering `app/views/articles/edit.html.erb` .
2012-10-17 13:15:55 +00:00
2020-10-28 22:04:03 +00:00
#### Using Partials to Share View Code
2012-10-17 13:15:55 +00:00
2020-10-28 22:04:03 +00:00
Our `edit` form will look the same as our `new` form. Even the code will be the
same, thanks to the Rails form builder and resourceful routing. The form builder
automatically configures the form to make the appropriate kind of request, based
on whether the model object has been previously saved.
2012-10-17 13:15:55 +00:00
2020-10-28 22:04:03 +00:00
Because the code will be the same, we're going to factor it out into a shared
view called a *partial* . Let's create `app/views/articles/_form.html.erb` with
the following contents:
2012-10-17 13:15:55 +00:00
```html+erb
2020-11-29 10:48:16 +00:00
< %= form_with model: article do |form| %>
2020-10-28 22:04:03 +00:00
< div >
2017-04-27 20:30:40 +00:00
< %= form.label :title %>< br >
< %= form.text_field :title %>
2020-12-20 04:48:41 +00:00
< % article.errors.full_messages_for(:title).each do |message| %>
2020-10-28 22:04:03 +00:00
< div > < %= message %>< / div >
< % end %>
< / div >
2012-10-17 13:15:55 +00:00
2020-10-28 22:04:03 +00:00
< div >
< %= form.label :body %>< br >
< %= form.text_area :body %>< br >
2020-12-20 04:48:41 +00:00
< % article.errors.full_messages_for(:body).each do |message| %>
2020-10-28 22:04:03 +00:00
< div > < %= message %>< / div >
< % end %>
< / div >
2012-10-17 13:15:55 +00:00
2020-10-28 22:04:03 +00:00
< div >
2017-04-27 20:30:40 +00:00
< %= form.submit %>
2020-10-28 22:04:03 +00:00
< / div >
2012-10-17 13:15:55 +00:00
< % end %>
```
2020-10-28 22:04:03 +00:00
The above code is the same as our form in `app/views/articles/new.html.erb` ,
except that all occurrences of `@article` have been replaced with `article` .
Because partials are shared code, it is best practice that they do not depend on
specific instance variables set by a controller action. Instead, we will pass
the article to the partial as a local variable.
2013-07-06 03:04:25 +00:00
2020-10-28 22:04:03 +00:00
Let's update `app/views/articles/new.html.erb` to use the partial via [`render`](
https://api.rubyonrails.org/classes/ActionView/Helpers/RenderingHelper.html#method-i-render):
2012-10-17 13:15:55 +00:00
```html+erb
2019-11-10 13:03:12 +00:00
< h1 > New Article< / h1 >
2012-10-17 13:15:55 +00:00
2020-10-28 22:04:03 +00:00
< %= render "form", article: @article %>
2012-10-17 13:15:55 +00:00
```
2020-10-28 22:04:03 +00:00
NOTE: A partial's filename must be prefixed **with** an underscore, e.g.
`_form.html.erb` . But when rendering, it is referenced **without** the
underscore, e.g. `render "form"` .
And now, let's create a very similar `app/views/articles/edit.html.erb` :
2012-10-17 13:15:55 +00:00
```html+erb
2019-11-10 13:03:12 +00:00
< h1 > Edit Article< / h1 >
2012-10-17 13:15:55 +00:00
2020-10-28 22:04:03 +00:00
< %= render "form", article: @article %>
2012-10-17 13:15:55 +00:00
```
2020-10-28 22:04:03 +00:00
TIP: To learn more about partials, see [Layouts and Rendering in Rails § Using
Partials](layouts_and_rendering.html#using-partials).
2020-10-28 22:04:25 +00:00
#### Finishing Up
We can now update an article by visiting its edit page, e.g.
< http: / / localhost:3000 / articles / 1 / edit > . To finish up, let's link to the edit
page from the bottom of `app/views/articles/show.html.erb` :
```html+erb
< h1 > < %= @article .title %></ h1 >
< p > < %= @article .body %></ p >
< ul >
< li > < %= link_to "Edit", edit_article_path(@article) %>< / li >
< / ul >
```
2020-10-28 22:06:07 +00:00
### Deleting an Article
2012-10-17 13:15:55 +00:00
2020-10-28 22:06:07 +00:00
Finally, we arrive at the "D" (Delete) of CRUD. Deleting a resource is a simpler
process than creating or updating. It only requires a route and a controller
action. And our resourceful routing (`resources :articles`) already provides the
route, which maps `DELETE /articles/:id` requests to the `destroy` action of
`ArticlesController` .
2012-10-17 13:15:55 +00:00
2020-10-28 22:06:07 +00:00
So, let's add a typical `destroy` action to `app/controllers/articles_controller.rb` ,
below the `update` action:
2014-04-29 14:56:43 +00:00
```ruby
class ArticlesController < ApplicationController
def index
@articles = Article.all
end
def show
@article = Article.find(params[:id])
end
def new
@article = Article.new
end
def create
@article = Article.new(article_params)
if @article .save
redirect_to @article
else
2020-10-28 22:06:07 +00:00
render :new
2014-04-29 14:56:43 +00:00
end
end
2020-10-28 22:06:07 +00:00
def edit
@article = Article.find(params[:id])
end
2014-04-29 14:56:43 +00:00
def update
@article = Article.find(params[:id])
if @article .update(article_params)
redirect_to @article
else
2020-10-28 22:06:07 +00:00
render :edit
2014-04-29 14:56:43 +00:00
end
end
def destroy
@article = Article.find(params[:id])
@article .destroy
2020-10-28 22:06:07 +00:00
redirect_to root_path
2014-04-29 14:56:43 +00:00
end
private
def article_params
2020-10-28 22:06:07 +00:00
params.require(:article).permit(:title, :body)
2014-04-29 14:56:43 +00:00
end
end
```
2020-10-28 22:06:07 +00:00
The `destroy` action fetches the article from the database, and calls [`destroy`](
https://api.rubyonrails.org/classes/ActiveRecord/Persistence.html#method-i-destroy)
on it. Then, it redirects the browser to the root path.
2012-10-17 13:15:55 +00:00
2020-10-28 22:06:07 +00:00
We have chosen to redirect to the root path because that is our main access
point for articles. But, in other circumstances, you might choose to redirect to
e.g. `articles_path` .
2012-10-17 13:15:55 +00:00
2020-10-28 22:06:07 +00:00
Now let's add a link at the bottom of `app/views/articles/show.html.erb` so that
we can delete an article from its own page:
2012-10-17 13:15:55 +00:00
2020-10-28 22:06:07 +00:00
```html+erb
< h1 > < %= @article .title %></ h1 >
2012-10-17 13:15:55 +00:00
2020-10-28 22:06:07 +00:00
< p > < %= @article .body %></ p >
2012-10-17 13:15:55 +00:00
2020-10-28 22:06:07 +00:00
< ul >
< li > < %= link_to "Edit", edit_article_path(@article) %>< / li >
< li > < %= link_to "Destroy", article_path(@article),
method: :delete,
data: { confirm: "Are you sure?" } %>< / li >
< / ul >
```
2012-10-17 13:15:55 +00:00
2020-10-28 22:06:07 +00:00
In the above code, we're passing a few additional options to `link_to` . The
`method: :delete` option causes the link to make a `DELETE` request instead of a
`GET` request. The `data: { confirm: "Are you sure?" }` option causes a
confirmation dialog to appear when the link is clicked. If the user cancels the
dialog, the request is aborted. Both of these options are powered by a feature
of Rails called *Unobtrusive JavaScript* (UJS). The JavaScript file that
implements these behaviors is included by default in fresh Rails applications.
2015-01-15 18:11:34 +00:00
2020-10-28 22:06:07 +00:00
TIP: To learn more about Unobtrusive JavaScript, see [Working With JavaScript in
Rails](working_with_javascript_in_rails.html).
2012-10-17 13:15:55 +00:00
2020-10-28 22:06:07 +00:00
And that's it! We can now list, show, create, update, and delete articles!
InCRUDable!
2012-10-17 13:15:55 +00:00
Adding a Second Model
---------------------
2013-09-12 16:15:23 +00:00
It's time to add a second model to the application. The second model will handle
2014-01-20 19:06:44 +00:00
comments on articles.
2012-10-17 13:15:55 +00:00
### Generating a Model
We're going to see the same generator that we used before when creating
2018-03-16 22:02:48 +00:00
the `Article` model. This time we'll create a `Comment` model to hold a
2015-03-24 00:01:15 +00:00
reference to an article. Run this command in your terminal:
2012-10-17 13:15:55 +00:00
```bash
2019-01-22 08:53:47 +00:00
$ bin/rails generate model Comment commenter:string body:text article:references
2012-10-17 13:15:55 +00:00
```
This command will generate four files:
| File | Purpose |
| -------------------------------------------- | ------------------------------------------------------------------------------------------------------ |
2014-01-20 19:06:44 +00:00
| db/migrate/20140120201010_create_comments.rb | Migration to create the comments table in your database (your name will include a different timestamp) |
2012-10-17 13:15:55 +00:00
| app/models/comment.rb | The Comment model |
2015-03-23 23:48:11 +00:00
| test/models/comment_test.rb | Testing harness for the comment model |
2012-10-17 13:15:55 +00:00
| test/fixtures/comments.yml | Sample comments for use in testing |
2012-12-03 01:11:16 +00:00
First, take a look at `app/models/comment.rb` :
2012-10-17 13:15:55 +00:00
```ruby
2015-12-17 10:30:30 +00:00
class Comment < ApplicationRecord
2014-01-20 19:06:44 +00:00
belongs_to :article
2012-10-17 13:15:55 +00:00
end
```
2014-01-20 19:06:44 +00:00
This is very similar to the `Article` model that you saw earlier. The difference
is the line `belongs_to :article` , which sets up an Active Record _association_ .
2012-10-17 13:15:55 +00:00
You'll learn a little about associations in the next section of this guide.
2016-02-02 20:45:12 +00:00
The (`:references`) keyword used in the bash command is a special data type for models.
2016-01-21 20:25:55 +00:00
It creates a new column on your database table with the provided model name appended with an `_id`
2017-06-30 10:57:00 +00:00
that can hold integer values. To get a better understanding, analyze the
`db/schema.rb` file after running the migration.
2016-01-21 20:25:55 +00:00
2012-10-17 13:15:55 +00:00
In addition to the model, Rails has also made a migration to create the
corresponding database table:
```ruby
2019-02-22 17:40:52 +00:00
class CreateComments < ActiveRecord::Migration [ 6 . 0 ]
2012-10-17 13:15:55 +00:00
def change
create_table :comments do |t|
t.string :commenter
t.text :body
2019-05-01 15:17:41 +00:00
t.references :article, null: false, foreign_key: true
2012-10-17 13:15:55 +00:00
2016-03-03 05:02:42 +00:00
t.timestamps
2012-10-17 13:15:55 +00:00
end
end
end
```
2015-06-28 09:52:59 +00:00
The `t.references` line creates an integer column called `article_id` , an index
2015-06-29 19:58:45 +00:00
for it, and a foreign key constraint that points to the `id` column of the `articles`
table. Go ahead and run the migration:
2012-10-17 13:15:55 +00:00
```bash
2019-01-22 08:53:47 +00:00
$ bin/rails db:migrate
2012-10-17 13:15:55 +00:00
```
Rails is smart enough to only execute the migrations that have not already been
run against the current database, so in this case you will just see:
2020-06-13 23:07:03 +00:00
```
2012-10-17 13:15:55 +00:00
== CreateComments: migrating =================================================
-- create_table(:comments)
2013-05-04 08:00:26 +00:00
-> 0.0115s
== CreateComments: migrated (0.0119s) ========================================
2012-10-17 13:15:55 +00:00
```
### Associating Models
Active Record associations let you easily declare the relationship between two
2014-01-20 19:06:44 +00:00
models. In the case of comments and articles, you could write out the
relationships this way:
2012-10-17 13:15:55 +00:00
2014-01-20 19:06:44 +00:00
* Each comment belongs to one article.
* One article can have many comments.
2012-10-17 13:15:55 +00:00
In fact, this is very close to the syntax that Rails uses to declare this
2013-09-12 16:15:23 +00:00
association. You've already seen the line of code inside the `Comment` model
2014-01-20 19:06:44 +00:00
(app/models/comment.rb) that makes each comment belong to an Article:
2012-10-17 13:15:55 +00:00
```ruby
2015-12-17 10:30:30 +00:00
class Comment < ApplicationRecord
2014-01-20 19:06:44 +00:00
belongs_to :article
2012-10-17 13:15:55 +00:00
end
```
2014-01-20 19:06:44 +00:00
You'll need to edit `app/models/article.rb` to add the other side of the
association:
2012-10-17 13:15:55 +00:00
```ruby
2015-12-17 10:30:30 +00:00
class Article < ApplicationRecord
2012-11-25 05:37:50 +00:00
has_many :comments
2020-10-28 22:07:09 +00:00
validates :title, presence: true
validates :body, presence: true, length: { minimum: 10 }
2012-10-17 13:15:55 +00:00
end
```
These two declarations enable a good bit of automatic behavior. For example, if
2014-01-20 19:06:44 +00:00
you have an instance variable `@article` containing an article, you can retrieve
all the comments belonging to that article as an array using
`@article.comments` .
2012-10-17 13:15:55 +00:00
TIP: For more information on Active Record associations, see the [Active Record
Associations](association_basics.html) guide.
### Adding a Route for Comments
2014-01-20 19:06:44 +00:00
As with the `welcome` controller, we will need to add a route so that Rails
knows where we would like to navigate to see `comments` . Open up the
2012-10-17 13:15:55 +00:00
`config/routes.rb` file again, and edit it as follows:
```ruby
2020-10-28 22:07:09 +00:00
Rails.application.routes.draw do
root "articles#index"
resources :articles do
resources :comments
end
2012-10-17 13:15:55 +00:00
end
```
2014-01-20 19:06:44 +00:00
This creates `comments` as a _nested resource_ within `articles` . This is
another part of capturing the hierarchical relationship that exists between
articles and comments.
2012-10-17 13:15:55 +00:00
2014-01-20 19:06:44 +00:00
TIP: For more information on routing, see the [Rails Routing ](routing.html )
guide.
2012-10-17 13:15:55 +00:00
### Generating a Controller
With the model in hand, you can turn your attention to creating a matching
controller. Again, we'll use the same generator we used before:
```bash
2019-01-22 08:53:47 +00:00
$ bin/rails generate controller Comments
2012-10-17 13:15:55 +00:00
```
2019-03-05 03:01:32 +00:00
This creates four files and one empty directory:
2012-10-17 13:15:55 +00:00
| File/Directory | Purpose |
| -------------------------------------------- | ---------------------------------------- |
| app/controllers/comments_controller.rb | The Comments controller |
| app/views/comments/ | Views of the controller are stored here |
2012-11-25 19:02:01 +00:00
| test/controllers/comments_controller_test.rb | The test for the controller |
2012-10-17 13:15:55 +00:00
| app/helpers/comments_helper.rb | A view helper file |
2016-11-06 20:12:06 +00:00
| app/assets/stylesheets/comments.scss | Cascading style sheet for the controller |
2012-10-17 13:15:55 +00:00
Like with any blog, our readers will create their comments directly after
2014-01-20 19:06:44 +00:00
reading the article, and once they have added their comment, will be sent back
to the article show page to see their comment now listed. Due to this, our
2012-10-17 13:15:55 +00:00
`CommentsController` is there to provide a method to create comments and delete
spam comments when they arrive.
2014-01-20 19:06:44 +00:00
So first, we'll wire up the Article show template
(`app/views/articles/show.html.erb`) to let us make a new comment:
2012-10-17 13:15:55 +00:00
```html+erb
2020-10-28 22:07:09 +00:00
< h1 > < %= @article .title %></ h1 >
2012-10-17 13:15:55 +00:00
2020-10-28 22:07:09 +00:00
< p > < %= @article .body %></ p >
< ul >
< li > < %= link_to "Edit", edit_article_path(@article) %>< / li >
< li > < %= link_to "Destroy", article_path(@article),
method: :delete,
data: { confirm: "Are you sure?" } %>< / li >
< / ul >
2012-10-17 13:15:55 +00:00
< h2 > Add a comment:< / h2 >
2020-11-29 10:48:16 +00:00
< %= form_with model: [ @article , @article .comments.build ] do |form| %>
2012-10-17 13:15:55 +00:00
< p >
2017-04-27 20:30:40 +00:00
< %= form.label :commenter %>< br >
< %= form.text_field :commenter %>
2012-10-17 13:15:55 +00:00
< / p >
< p >
2017-04-27 20:30:40 +00:00
< %= form.label :body %>< br >
< %= form.text_area :body %>
2012-10-17 13:15:55 +00:00
< / p >
< p >
2017-04-27 20:30:40 +00:00
< %= form.submit %>
2012-10-17 13:15:55 +00:00
< / p >
< % end %>
```
2014-01-20 19:06:44 +00:00
This adds a form on the `Article` show page that creates a new comment by
2017-04-27 20:30:40 +00:00
calling the `CommentsController` `create` action. The `form_with` call here uses
2014-01-20 19:06:44 +00:00
an array, which will build a nested route, such as `/articles/1/comments` .
2012-10-17 13:15:55 +00:00
Let's wire up the `create` in `app/controllers/comments_controller.rb` :
```ruby
class CommentsController < ApplicationController
def create
2014-01-20 19:06:44 +00:00
@article = Article.find(params[:article_id])
@comment = @article .comments.create(comment_params)
redirect_to article_path(@article)
2012-10-17 13:15:55 +00:00
end
2013-06-29 20:03:27 +00:00
private
def comment_params
params.require(:comment).permit(:commenter, :body)
end
2012-10-17 13:15:55 +00:00
end
```
2014-01-20 19:06:44 +00:00
You'll see a bit more complexity here than you did in the controller for
articles. That's a side-effect of the nesting that you've set up. Each request
for 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 the
article in question.
2012-10-17 13:15:55 +00:00
In addition, the code takes advantage of some of the methods available for an
2014-01-20 19:06:44 +00:00
association. We use the `create` method on `@article.comments` to create and
save the comment. This will automatically link the comment so that it belongs to
that particular article.
2012-10-17 13:15:55 +00:00
2014-01-20 19:06:44 +00:00
Once we have made the new comment, we send the user back to the original article
using the `article_path(@article)` helper. As we have already seen, this calls
the `show` action of the `ArticlesController` which in turn renders the
`show.html.erb` template. This is where we want the comment to show, so let's
add that to the `app/views/articles/show.html.erb` .
2012-10-17 13:15:55 +00:00
```html+erb
2020-10-28 22:07:09 +00:00
< h1 > < %= @article .title %></ h1 >
2012-10-17 13:15:55 +00:00
2020-10-28 22:07:09 +00:00
< p > < %= @article .body %></ p >
< ul >
< li > < %= link_to "Edit", edit_article_path(@article) %>< / li >
< li > < %= link_to "Destroy", article_path(@article),
method: :delete,
data: { confirm: "Are you sure?" } %>< / li >
< / ul >
2012-10-17 13:15:55 +00:00
< h2 > Comments< / h2 >
2014-01-20 19:06:44 +00:00
< % @article .comments.each do |comment| %>
2012-10-17 13:15:55 +00:00
< p >
< strong > Commenter:< / strong >
< %= comment.commenter %>
< / p >
< p >
< strong > Comment:< / strong >
< %= comment.body %>
< / p >
< % end %>
< h2 > Add a comment:< / h2 >
2020-11-29 10:48:16 +00:00
< %= form_with model: [ @article , @article .comments.build ] do |form| %>
2012-10-17 13:15:55 +00:00
< p >
2017-04-27 20:30:40 +00:00
< %= form.label :commenter %>< br >
< %= form.text_field :commenter %>
2012-10-17 13:15:55 +00:00
< / p >
< p >
2017-04-27 20:30:40 +00:00
< %= form.label :body %>< br >
< %= form.text_area :body %>
2012-10-17 13:15:55 +00:00
< / p >
< p >
2017-04-27 20:30:40 +00:00
< %= form.submit %>
2012-10-17 13:15:55 +00:00
< / p >
< % end %>
```
2014-01-20 19:06:44 +00:00
Now you can add articles and comments to your blog and have them show up in the
2012-10-17 13:15:55 +00:00
right places.
2014-01-20 19:06:44 +00:00
![Article with Comments ](images/getting_started/article_with_comments.png )
2012-10-17 13:15:55 +00:00
Refactoring
-----------
2014-01-20 19:06:44 +00:00
Now that we have articles and comments working, take a look at the
`app/views/articles/show.html.erb` template. It is getting long and awkward. We
can use partials to clean it up.
2012-10-17 13:15:55 +00:00
### Rendering Partial Collections
2014-01-20 19:06:44 +00:00
First, we will make a comment partial to extract showing all the comments for
the article. Create the file `app/views/comments/_comment.html.erb` and put the
2012-10-17 13:15:55 +00:00
following into it:
```html+erb
< p >
< strong > Commenter:< / strong >
< %= comment.commenter %>
< / p >
< p >
< strong > Comment:< / strong >
< %= comment.body %>
< / p >
```
2014-01-20 19:06:44 +00:00
Then you can change `app/views/articles/show.html.erb` to look like the
2012-10-17 13:15:55 +00:00
following:
```html+erb
2020-10-28 22:07:09 +00:00
< h1 > < %= @article .title %></ h1 >
2012-10-17 13:15:55 +00:00
2020-10-28 22:07:09 +00:00
< p > < %= @article .body %></ p >
< ul >
< li > < %= link_to "Edit", edit_article_path(@article) %>< / li >
< li > < %= link_to "Destroy", article_path(@article),
method: :delete,
data: { confirm: "Are you sure?" } %>< / li >
< / ul >
2012-10-17 13:15:55 +00:00
< h2 > Comments< / h2 >
2014-01-20 19:06:44 +00:00
< %= render @article .comments %>
2012-10-17 13:15:55 +00:00
< h2 > Add a comment:< / h2 >
2020-11-29 10:48:16 +00:00
< %= form_with model: [ @article , @article .comments.build ] do |form| %>
2012-10-17 13:15:55 +00:00
< p >
2017-04-27 20:30:40 +00:00
< %= form.label :commenter %>< br >
< %= form.text_field :commenter %>
2012-10-17 13:15:55 +00:00
< / p >
< p >
2017-04-27 20:30:40 +00:00
< %= form.label :body %>< br >
< %= form.text_area :body %>
2012-10-17 13:15:55 +00:00
< / p >
< p >
2017-04-27 20:30:40 +00:00
< %= form.submit %>
2012-10-17 13:15:55 +00:00
< / p >
< % end %>
```
This will now render the partial in `app/views/comments/_comment.html.erb` once
2014-01-20 19:06:44 +00:00
for each comment that is in the `@article.comments` collection. As the `render`
method iterates over the `@article.comments` collection, it assigns each
2012-10-17 13:15:55 +00:00
comment to a local variable named the same as the partial, in this case
2018-03-16 22:02:48 +00:00
`comment` , which is then available in the partial for us to show.
2012-10-17 13:15:55 +00:00
### Rendering a Partial Form
Let us also move that new comment section out to its own partial. Again, you
create a file `app/views/comments/_form.html.erb` containing:
```html+erb
2020-11-29 10:48:16 +00:00
< %= form_with model: [ @article , @article .comments.build ] do |form| %>
2012-10-17 13:15:55 +00:00
< p >
2017-04-27 20:30:40 +00:00
< %= form.label :commenter %>< br >
< %= form.text_field :commenter %>
2012-10-17 13:15:55 +00:00
< / p >
< p >
2017-04-27 20:30:40 +00:00
< %= form.label :body %>< br >
< %= form.text_area :body %>
2012-10-17 13:15:55 +00:00
< / p >
< p >
2017-04-27 20:30:40 +00:00
< %= form.submit %>
2012-10-17 13:15:55 +00:00
< / p >
< % end %>
```
2014-01-20 19:06:44 +00:00
Then you make the `app/views/articles/show.html.erb` look like the following:
2012-10-17 13:15:55 +00:00
```html+erb
2020-10-28 22:07:09 +00:00
< h1 > < %= @article .title %></ h1 >
2012-10-17 13:15:55 +00:00
2020-10-28 22:07:09 +00:00
< p > < %= @article .body %></ p >
< ul >
< li > < %= link_to "Edit", edit_article_path(@article) %>< / li >
< li > < %= link_to "Destroy", article_path(@article),
method: :delete,
data: { confirm: "Are you sure?" } %>< / li >
< / ul >
2012-10-17 13:15:55 +00:00
2013-01-22 04:42:06 +00:00
< h2 > Comments< / h2 >
2014-01-20 19:06:44 +00:00
< %= render @article .comments %>
2013-01-22 04:42:06 +00:00
2012-10-17 13:15:55 +00:00
< h2 > Add a comment:< / h2 >
2014-06-22 01:23:48 +00:00
< %= render 'comments/form' %>
2012-10-17 13:15:55 +00:00
```
The second render just defines the partial template we want to render,
`comments/form` . Rails is smart enough to spot the forward slash in that
string and realize that you want to render the `_form.html.erb` file in
the `app/views/comments` directory.
2014-01-20 19:06:44 +00:00
The `@article` object is available to any partials rendered in the view because
we defined it as an instance variable.
2012-10-17 13:15:55 +00:00
2020-06-23 05:10:27 +00:00
### Using Concerns
2020-07-16 04:01:53 +00:00
Concerns are a way to make large controllers or models easier to understand and manage. This also has the advantage of reusability when multiple models (or controllers) share the same concerns. Concerns are implemented using modules that contain methods representing a well-defined slice of the functionality that a model or controller is responsible for. In other languages, modules are often known as mixins.
2020-06-23 05:10:27 +00:00
2020-07-16 04:01:53 +00:00
You can use concerns in your controller or model the same way you would use any module. When you first created your app with `rails new blog` , two folders were created within `app/` along with the rest:
2020-06-23 05:10:27 +00:00
2020-12-25 17:17:01 +00:00
```
app/controllers/concerns
app/models/concerns
```
2020-06-23 05:10:27 +00:00
2020-07-07 04:28:49 +00:00
A given blog article might have various statuses - for instance, it might be visible to everyone (i.e. `public` ), or only visible to the author (i.e. `private` ). It may also be hidden to all but still retrievable (i.e. `archived` ). Comments may similarly be hidden or visible. This could be represented using a `status` column in each model.
2020-06-23 05:10:27 +00:00
Within the `article` model, after running a migration to add a `status` column, you might add:
```ruby
class Article < ApplicationRecord
has_many :comments
2020-10-28 22:07:09 +00:00
validates :title, presence: true
validates :body, presence: true, length: { minimum: 10 }
2020-06-23 05:10:27 +00:00
VALID_STATUSES = ['public', 'private', 'archived']
2020-12-13 16:02:53 +00:00
validates :status, inclusion: { in: VALID_STATUSES }
2020-06-23 05:10:27 +00:00
2020-09-23 00:22:17 +00:00
def archived?
2020-06-23 05:10:27 +00:00
status == 'archived'
end
end
```
and in the `Comment` model:
```ruby
class Comment < ApplicationRecord
belongs_to :article
VALID_STATUSES = ['public', 'private', 'archived']
2020-12-13 16:02:53 +00:00
validates :status, inclusion: { in: VALID_STATUSES }
2020-06-23 05:10:27 +00:00
def archived?
status == 'archived'
end
end
```
Then, in our `index` action template (`app/views/articles/index.html.erb`) we would use the `archived?` method to avoid displaying any article that is archived:
```html+erb
2020-10-28 22:07:09 +00:00
< h1 > Articles< / h1 >
2020-06-23 05:10:27 +00:00
2020-10-28 22:07:09 +00:00
< ul >
2020-06-23 05:10:27 +00:00
< % @articles .each do |article| %>
2020-09-23 00:22:17 +00:00
< % unless article.archived? %>
2020-10-28 22:07:09 +00:00
< li >
< %= link_to article.title, article %>
< / li >
2020-06-23 05:10:27 +00:00
< % end %>
< % end %>
2020-10-28 22:07:09 +00:00
< / ul >
< %= link_to "New Article", new_article_path %>
2020-06-23 05:10:27 +00:00
```
2020-07-16 04:01:53 +00:00
However, if you look again at our models now, you can see that the logic is duplicated. If in the future we increase the functionality of our blog - to include private messages, for instance - we might find ourselves duplicating the logic yet again. This is where concerns come in handy.
2020-06-23 05:10:27 +00:00
2020-07-14 03:51:26 +00:00
A concern is only responsible for a focused subset of the model's responsibility; the methods in our concern will all be related to the visibility of a model. Let's call our new concern (module) `Visible` . We can create a new file inside `app/models/concerns` called `visible.rb` , and store all of the status methods that were duplicated in the models.
2020-06-23 05:10:27 +00:00
2020-07-07 04:28:49 +00:00
`app/models/concerns/visible.rb`
2020-06-23 05:10:27 +00:00
```ruby
2020-07-07 04:28:49 +00:00
module Visible
2020-06-23 05:10:27 +00:00
def archived?
status == 'archived'
end
end
```
2020-07-07 04:28:49 +00:00
We can add our status validation to the concern, but this is slightly more complex as validations are methods called at the class level. The `ActiveSupport::Concern` ([API Guide](https://api.rubyonrails.org/classes/ActiveSupport/Concern.html)) gives us a simpler way to include them:
2020-06-23 05:10:27 +00:00
```ruby
2020-07-07 04:28:49 +00:00
module Visible
2020-10-01 12:44:37 +00:00
extend ActiveSupport::Concern
2020-06-23 05:10:27 +00:00
2020-12-15 09:33:21 +00:00
VALID_STATUSES = ['public', 'private', 'archived']
2020-06-23 05:10:27 +00:00
2020-12-15 09:33:21 +00:00
included do
2020-12-13 16:02:53 +00:00
validates :status, inclusion: { in: VALID_STATUSES }
2020-06-23 05:10:27 +00:00
end
def archived?
status == 'archived'
end
end
```
2020-07-07 04:28:49 +00:00
Now, we can remove the duplicated logic from each model and instead include our new `Visible` module:
2020-06-23 05:10:27 +00:00
In `app/models/article.rb` :
2020-09-23 00:22:17 +00:00
2020-06-23 05:10:27 +00:00
```ruby
class Article < ApplicationRecord
2020-07-07 04:28:49 +00:00
include Visible
2020-06-23 05:10:27 +00:00
has_many :comments
2020-10-28 22:07:09 +00:00
validates :title, presence: true
validates :body, presence: true, length: { minimum: 10 }
2020-06-23 05:10:27 +00:00
end
```
and in `app/models/comment.rb` :
```ruby
class Comment < ApplicationRecord
2020-07-07 04:28:49 +00:00
include Visible
2020-06-23 05:10:27 +00:00
belongs_to :article
end
```
2020-07-16 04:01:53 +00:00
Class methods can also be added to concerns. If we want a count of public articles or comments to display on our main page, we might add a class method to Visible as follows:
2020-07-07 04:28:49 +00:00
```ruby
module Visible
2020-10-01 12:44:37 +00:00
extend ActiveSupport::Concern
2020-07-07 04:28:49 +00:00
VALID_STATUSES = ['public', 'private', 'archived']
included do
2020-12-13 16:02:53 +00:00
validates :status, inclusion: { in: VALID_STATUSES }
2020-07-07 04:28:49 +00:00
end
class_methods do
def public_count
2020-07-16 04:01:53 +00:00
where(status: 'public').count
2020-07-07 04:28:49 +00:00
end
end
def archived?
status == 'archived'
end
end
```
Then in the view, you can call it like any class method:
```html+erb
2020-10-28 22:07:09 +00:00
< h1 > Articles< / h1 >
2020-07-07 04:28:49 +00:00
2020-10-28 22:07:09 +00:00
Our blog has < %= Article.public_count %> articles and counting!
< ul >
2020-07-07 04:28:49 +00:00
< % @articles .each do |article| %>
2020-10-28 22:07:09 +00:00
< li >
< %= link_to article.title, article %>
< / li >
2020-07-07 04:28:49 +00:00
< % end %>
2020-10-28 22:07:09 +00:00
< / ul >
< %= link_to "New Article", new_article_path %>
2020-07-07 04:28:49 +00:00
```
2020-06-23 05:10:27 +00:00
2020-12-15 09:33:21 +00:00
There are a few more steps to be carried out before our application works with the addition of `status` column. First, let's run the following migrations to add `status` to `Articles` and `Comments` :
```bash
$ bin/rails generate migration AddStatusToArticles status:string
$ bin/rails generate migration AddStatusToComments status:string
```
TIP: To learn more about migrations, see [Active Record Migrations](
active_record_migrations.html).
We also have to permit the `:status` key as part of the strong parameter, in `app/controllers/articles_controller.rb` :
```ruby
2020-12-30 05:50:34 +00:00
private
2020-12-15 09:33:21 +00:00
def article_params
params.require(:comment).permit(:commenter, :body, :status)
end
```
and in `app/controllers/comments_controller.rb` :
```ruby
2020-12-30 05:50:34 +00:00
private
2020-12-15 09:33:21 +00:00
def comment_params
params.require(:comment).permit(:commenter, :body, :status)
end
```
To finish up, we will add a select box to the forms, and let the user select the status when they create a new article or post a new comment. We can also specify the default status as `public` . In `app/views/articles/_form.html.erb` , we can add:
```html+erb
< div >
< %= form.label :status %>< br >
< %= form.select :status, ['public', 'private', 'archived'], selected: 'public' %>
< / div >
```
and in `app/views/comments/_form.html.erb` :
2020-12-15 10:09:27 +00:00
2020-12-15 09:33:21 +00:00
```html+erb
< p >
< %= form.label :status %>< br >
< %= form.select :status, ['public', 'private', 'archived'], selected: 'public' %>
< / p >
```
2012-10-17 13:15:55 +00:00
Deleting Comments
-----------------
Another important feature of a blog is being able to delete spam comments. To do
2013-12-23 17:45:15 +00:00
this, we need to implement a link of some sort in the view and a `destroy`
action in the `CommentsController` .
2012-10-17 13:15:55 +00:00
So first, let's add the delete link in the
`app/views/comments/_comment.html.erb` partial:
```html+erb
< p >
< strong > Commenter:< / strong >
< %= comment.commenter %>
< / p >
< p >
< strong > Comment:< / strong >
< %= comment.body %>
< / p >
< p >
2014-01-20 19:06:44 +00:00
< %= link_to 'Destroy Comment', [comment.article, comment],
2020-12-25 17:17:01 +00:00
method: :delete,
data: { confirm: "Are you sure?" } %>
2012-10-17 13:15:55 +00:00
< / p >
```
Clicking this new "Destroy Comment" link will fire off a `DELETE
2014-01-20 19:06:44 +00:00
/articles/:article_id/comments/:id` to our `CommentsController` , which can then
use this to find the comment we want to delete, so let's add a `destroy` action
to our controller (`app/controllers/comments_controller.rb`):
2012-10-17 13:15:55 +00:00
```ruby
class CommentsController < ApplicationController
def create
2014-01-20 19:06:44 +00:00
@article = Article.find(params[:article_id])
@comment = @article .comments.create(comment_params)
redirect_to article_path(@article)
2012-10-17 13:15:55 +00:00
end
def destroy
2014-01-20 19:06:44 +00:00
@article = Article.find(params[:article_id])
@comment = @article .comments.find(params[:id])
2012-10-17 13:15:55 +00:00
@comment .destroy
2014-01-20 19:06:44 +00:00
redirect_to article_path(@article)
2012-10-17 13:15:55 +00:00
end
2013-06-29 20:03:27 +00:00
private
def comment_params
params.require(:comment).permit(:commenter, :body)
end
2012-10-17 13:15:55 +00:00
end
```
2014-01-20 19:06:44 +00:00
The `destroy` action will find the article we are looking at, locate the comment
within the `@article.comments` collection, and then remove it from the
database and send us back to the show action for the article.
2012-10-17 13:15:55 +00:00
### Deleting Associated Objects
2014-04-22 07:40:32 +00:00
If you delete an article, its associated comments will also need to be
2014-04-29 14:56:43 +00:00
deleted, otherwise they would simply occupy space in the database. Rails allows
2014-01-20 19:06:44 +00:00
you to use the `dependent` option of an association to achieve this. Modify the
Article model, `app/models/article.rb` , as follows:
2012-10-17 13:15:55 +00:00
```ruby
2015-12-17 10:30:30 +00:00
class Article < ApplicationRecord
2020-07-07 04:28:49 +00:00
include Visible
2020-06-23 05:10:27 +00:00
2012-11-25 05:57:21 +00:00
has_many :comments, dependent: :destroy
2020-10-28 22:07:09 +00:00
validates :title, presence: true
validates :body, presence: true, length: { minimum: 10 }
2012-10-17 13:15:55 +00:00
end
```
Security
--------
2013-08-04 07:38:47 +00:00
### Basic Authentication
2014-04-22 07:40:32 +00:00
If you were to publish your blog online, anyone would be able to add, edit and
2014-01-20 19:06:44 +00:00
delete articles or delete comments.
2012-10-17 13:15:55 +00:00
2019-12-12 19:23:48 +00:00
Rails provides an HTTP authentication system that will work nicely in
2012-10-17 13:15:55 +00:00
this situation.
2014-04-22 07:40:32 +00:00
In the `ArticlesController` we need to have a way to block access to the
various actions if the person is not authenticated. Here we can use the Rails
`http_basic_authenticate_with` method, which allows access to the requested
2012-10-17 13:15:55 +00:00
action if that method allows it.
To use the authentication system, we specify it at the top of our
2014-04-22 07:40:32 +00:00
`ArticlesController` 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:
2012-10-17 13:15:55 +00:00
```ruby
2014-01-20 19:06:44 +00:00
class ArticlesController < ApplicationController
2012-10-17 13:15:55 +00:00
http_basic_authenticate_with name: "dhh", password: "secret", except: [:index, :show]
def index
2014-01-20 19:06:44 +00:00
@articles = Article.all
2012-10-17 13:15:55 +00:00
end
2015-05-06 08:43:33 +00:00
# snippet for brevity
2012-10-17 13:15:55 +00:00
```
2014-01-20 19:06:44 +00:00
We also want to allow only authenticated users to delete comments, so in the
2012-12-03 01:11:16 +00:00
`CommentsController` (`app/controllers/comments_controller.rb`) we write:
2012-10-17 13:15:55 +00:00
```ruby
class CommentsController < ApplicationController
http_basic_authenticate_with name: "dhh", password: "secret", only: :destroy
def create
2014-01-20 19:06:44 +00:00
@article = Article.find(params[:article_id])
2014-04-29 14:56:43 +00:00
# ...
2012-10-17 13:15:55 +00:00
end
2013-09-27 06:55:06 +00:00
2015-05-06 08:43:33 +00:00
# snippet for brevity
2012-10-17 13:15:55 +00:00
```
2014-01-20 19:06:44 +00:00
Now if you try to create a new article, you will be greeted with a basic HTTP
2014-06-29 02:26:35 +00:00
Authentication challenge:
2012-10-17 13:15:55 +00:00
2013-04-28 18:43:13 +00:00
![Basic HTTP Authentication Challenge ](images/getting_started/challenge.png )
2012-10-17 13:15:55 +00:00
2013-08-04 07:38:47 +00:00
Other authentication methods are available for Rails applications. Two popular
2014-01-20 19:06:44 +00:00
authentication add-ons for Rails are the
[Devise ](https://github.com/plataformatec/devise ) rails engine and
the [Authlogic ](https://github.com/binarylogic/authlogic ) gem,
2013-08-04 07:38:47 +00:00
along with a number of others.
### Other Security Considerations
Security, especially in web applications, is a broad and detailed area. Security
2013-09-12 16:15:23 +00:00
in your Rails application is covered in more depth in
2014-06-29 02:26:35 +00:00
the [Ruby on Rails Security Guide ](security.html ).
2013-08-04 07:38:47 +00:00
2012-10-17 13:15:55 +00:00
What's Next?
------------
Now that you've seen your first Rails application, you should feel free to
2014-12-30 19:13:20 +00:00
update it and experiment on your own.
2018-03-16 22:02:48 +00:00
Remember, you don't have to do everything without help. As you need assistance
2014-12-30 19:13:20 +00:00
getting up and running with Rails, feel free to consult these support
resources:
2012-10-17 13:15:55 +00:00
2014-06-29 02:26:35 +00:00
* The [Ruby on Rails Guides ](index.html )
2020-03-26 06:21:37 +00:00
* The [Ruby on Rails mailing list ](https://discuss.rubyonrails.org/c/rubyonrails-talk )
2012-10-17 13:15:55 +00:00
* The [#rubyonrails ](irc://irc.freenode.net/#rubyonrails ) channel on irc.freenode.net
Configuration Gotchas
---------------------
The easiest way to work with Rails is to store all external data as UTF-8. If
you don't, Ruby libraries and Rails will often be able to convert your native
data into UTF-8, but this doesn't always work reliably, so you're better off
ensuring that all external data is UTF-8.
If you have made a mistake in this area, the most common symptom is a black
diamond with a question mark inside appearing in the browser. Another common
symptom is characters like "ü" appearing instead of "ü". Rails takes a number
of internal steps to mitigate common causes of these problems that can be
automatically detected and corrected. However, if you have external data that is
not stored as UTF-8, it can occasionally result in these kinds of issues that
cannot be automatically detected by Rails and corrected.
Two very common sources of data that are not UTF-8:
2014-01-20 19:06:44 +00:00
* Your text editor: Most text editors (such as TextMate), default to saving
files as UTF-8. If your text editor does not, this can result in special
characters that you enter in your templates (such as é) to appear as a diamond
with a question mark inside in the browser. This also applies to your i18n
translation files. Most editors that do not already default to UTF-8 (such as
some versions of Dreamweaver) offer a way to change the default to UTF-8. Do
so.
* Your database: Rails defaults to converting data from your database into UTF-8
at the boundary. However, if your database is not using UTF-8 internally, it
may 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 enters
the database. If possible, use UTF-8 as the internal storage of your database.