diff --git a/guides/assets/images/getting_started/confirm_dialog.png b/guides/assets/images/getting_started/confirm_dialog.png deleted file mode 100644 index ce65734e6c..0000000000 Binary files a/guides/assets/images/getting_started/confirm_dialog.png and /dev/null differ diff --git a/guides/assets/images/getting_started/forbidden_attributes_for_new_article.png b/guides/assets/images/getting_started/forbidden_attributes_for_new_article.png deleted file mode 100644 index 50b178808e..0000000000 Binary files a/guides/assets/images/getting_started/forbidden_attributes_for_new_article.png and /dev/null differ diff --git a/guides/assets/images/getting_started/form_with_errors.png b/guides/assets/images/getting_started/form_with_errors.png deleted file mode 100644 index 6eefd2885a..0000000000 Binary files a/guides/assets/images/getting_started/form_with_errors.png and /dev/null differ diff --git a/guides/assets/images/getting_started/index_action_with_edit_link.png b/guides/assets/images/getting_started/index_action_with_edit_link.png deleted file mode 100644 index a2a087a598..0000000000 Binary files a/guides/assets/images/getting_started/index_action_with_edit_link.png and /dev/null differ diff --git a/guides/assets/images/getting_started/new_article.png b/guides/assets/images/getting_started/new_article.png deleted file mode 100644 index 6edcc161b6..0000000000 Binary files a/guides/assets/images/getting_started/new_article.png and /dev/null differ diff --git a/guides/assets/images/getting_started/routing_error_no_controller.png b/guides/assets/images/getting_started/routing_error_no_controller.png deleted file mode 100644 index 52150f0426..0000000000 Binary files a/guides/assets/images/getting_started/routing_error_no_controller.png and /dev/null differ diff --git a/guides/assets/images/getting_started/show_action_for_articles.png b/guides/assets/images/getting_started/show_action_for_articles.png deleted file mode 100644 index 68837131f7..0000000000 Binary files a/guides/assets/images/getting_started/show_action_for_articles.png and /dev/null differ diff --git a/guides/assets/images/getting_started/template_is_missing_articles_new.png b/guides/assets/images/getting_started/template_is_missing_articles_new.png deleted file mode 100644 index 8adcfcf0d7..0000000000 Binary files a/guides/assets/images/getting_started/template_is_missing_articles_new.png and /dev/null differ diff --git a/guides/assets/images/getting_started/unknown_action_create_for_articles.png b/guides/assets/images/getting_started/unknown_action_create_for_articles.png deleted file mode 100644 index 7b385ef9da..0000000000 Binary files a/guides/assets/images/getting_started/unknown_action_create_for_articles.png and /dev/null differ diff --git a/guides/assets/images/getting_started/unknown_action_new_for_articles.png b/guides/assets/images/getting_started/unknown_action_new_for_articles.png deleted file mode 100644 index f7e7464d61..0000000000 Binary files a/guides/assets/images/getting_started/unknown_action_new_for_articles.png and /dev/null differ diff --git a/guides/source/getting_started.md b/guides/source/getting_started.md index 4b79043add..93239176b5 100644 --- a/guides/source/getting_started.md +++ b/guides/source/getting_started.md @@ -30,8 +30,8 @@ for learning Ruby: * [Official Ruby Programming Language website](https://www.ruby-lang.org/en/documentation/) * [List of Free Programming Books](https://github.com/EbookFoundation/free-programming-books/blob/master/free-programming-books.md#ruby) -Be aware that some resources, while still excellent, cover versions of Ruby as old as -1.6, and commonly 1.8, and will not include some syntax that you will see in day-to-day +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 development with Rails. What is Rails? @@ -63,6 +63,7 @@ The Rails philosophy includes two major guiding principles: Creating a New Rails Project ---------------------------- + 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. @@ -71,9 +72,9 @@ By following along with this guide, you'll create a Rails project called `blog`, a (very) simple weblog. Before you can start building the application, you need to make sure that you have Rails itself installed. -TIP: The examples below use `$` to represent your terminal prompt in a UNIX-like OS, +NOTE: 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>` +your prompt will look something like `C:\source_code>`. ### Installing Rails @@ -87,8 +88,8 @@ proper prerequisites installed. These include: #### Installing Ruby -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 +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 dollar sign `$` should be run in the command line. Verify that you have a current version of Ruby installed: @@ -170,7 +171,7 @@ which will provide you with the foundation of a fresh Rails application so that you don't have to write it yourself. To use this generator, open a terminal, navigate to a directory where you have -rights to create files, and type: +rights to create files, and run: ```bash $ rails new blog @@ -182,10 +183,11 @@ install the gem dependencies that are already mentioned in `Gemfile` using 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` -and `listen` gems which you can do by running `rails new blog --skip-spring --skip-listen`. +and `listen` gems which you can do by running `rails new blog --skip-spring --skip-listen` +instead. TIP: You can see all of the command line options that the Rails application -builder accepts by running `rails new -h`. +generator accepts by running `rails new --help`. After you create the blog application, switch to its folder: @@ -193,30 +195,30 @@ 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 make +The `blog` directory will have a number of generated files and folders that make 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 -of the files and folders that Rails created by default: +of the files and folders that Rails creates by default: | File/Folder | Purpose | | ----------- | ------- | |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.| -|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/|Configure 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/).| +|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/).| |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](https://bundler.io).| |lib/|Extended modules for your application.| |log/|Application log files.| |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/).| -|public/|The only folder seen by the world as-is. Contains static files and compiled assets.| +|public/|Contains static files and compiled assets. When your app is running, this directory will be exposed as-is.| |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.| |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.| |storage/|Active Storage files for Disk Service. This is covered in [Active Storage Overview](active_storage_overview.html).| |test/|Unit tests, fixtures, and other test apparatus. These are covered in [Testing Rails Applications](testing.html).| |tmp/|Temporary files (like cache and pid files).| |vendor/|A place for all third-party code. In a typical Rails application this includes vendored gems.| -|.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. +|.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.| |.ruby-version|This file contains the default Ruby version.| Hello, Rails! @@ -229,7 +231,7 @@ get your Rails application server running. 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 -following in the `blog` directory: +following command in the `blog` directory: ```bash $ bin/rails server @@ -246,16 +248,14 @@ Usually macOS and Windows come with a JavaScript runtime installed. default to the `Gemfile` in apps generated under JRuby. You can investigate all the supported runtimes at [ExecJS](https://github.com/rails/execjs#readme). -This will fire up Puma, a web server distributed with Rails by default. To see +This will start up Puma, a web server distributed with Rails by default. To see your application in action, open a browser window and navigate to . You should see the Rails default information page: ![Yay! You're on Rails! screenshot](images/getting_started/rails_welcome.png) -TIP: To stop the web server, hit Ctrl+C in the terminal window where it's -running. To verify the server has stopped you should see your command prompt -cursor again. For most UNIX-like systems including macOS this will be a -dollar sign `$`. In the development environment, Rails does not generally +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 require you to restart the server; changes you make in files will be automatically picked up by the server. @@ -265,24 +265,19 @@ enough to serve a page. ### Say "Hello", Rails -To get Rails saying "Hello", you need to create at minimum a _route_, a _controller_ and a _view_. +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. -A controller's purpose is to receive specific requests for the application. -_Routing_ decides which controller receives which requests. Often, there is more -than one route to each controller, and different routes can be served by -different _actions_. Each action's purpose is to collect information to provide -it to a view. +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. -A view's purpose is to display this information in a human readable format. An -important distinction to make is that the _controller_, not the view, -is where information is collected. The view should just display that information. -By default, view templates are written in a language called eRuby (Embedded -Ruby) which is processed by the request cycle in Rails before being sent to the -user. - -When we make a request to our Rails application, we do so by making a request -to a particular _route_. To start off, let's create a route in -`config/routes.rb`: +Let's start by adding a route to our routes file, `config/routes.rb`, at the +top of the `Rails.application.routes.draw` block: ```ruby Rails.application.routes.draw do @@ -292,33 +287,21 @@ Rails.application.routes.draw do end ``` -This is your application's _routing file_ which holds entries in a special [DSL -(domain-specific -language)](https://en.wikipedia.org/wiki/Domain-specific_language) that tells -Rails how to connect incoming requests to controllers and actions. +The route above declares that `GET /articles` requests are mapped to the `index` +action of `ArticlesController`. -The line that we have just added says that we are going to match a `GET -/articles` request to `articles#index`. This string passed as the `to` option -represents the _controller_ and _action_ that will be responsible for handling -this request. - -Controllers are classes that group together common methods for handling a -particular _resource_. The methods inside controllers are given the name -"actions", as they _act upon_ requests as they come in. - -To create a new controller, you will need to run the "controller" generator and -tell it you want a controller called "articles" with an action called "index", -just like this: +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): ```bash -$ bin/rails generate controller articles index +$ bin/rails generate controller Articles index --skip-routes ``` -Rails will create several files and a route for you. +Rails will create several files for you: ``` create app/controllers/articles_controller.rb - route get 'articles/index' invoke erb create app/views/articles create app/views/articles/index.html.erb @@ -332,10 +315,8 @@ invoke scss create app/assets/stylesheets/articles.scss ``` -Most important of these is the controller, located at -`app/controllers/articles_controller.rb`. - -Let's look at that controller now: +The most important of these is the controller file, +`app/controllers/articles_controller.rb`. Let's take a look at it: ```ruby class ArticlesController < ApplicationController @@ -344,426 +325,105 @@ class ArticlesController < ApplicationController end ``` -This controller defines a single action, or "method" in common Ruby terms, -called `index`. This action is where we would define any logic that we would -want to happen when a request comes in to this action. Right at this moment, we -don't want this action to do anything, and so we'll keep it blank for now. +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. -When an action is left blank like this, Rails will default to rendering a view -that matches the name of the controller and the name of the action. Views in a -Rails application live in `app/views`, and so the default view for this action -is going to be `app/views/articles/index.html.erb`. - -Open the `app/views/articles/index.html.erb` file in your text editor. Delete all -of the existing code in the file, and replace it with the following single line -of code: +Let's open `app/views/articles/index.html.erb`, and replace its contents with: ```html

Hello, Rails!

``` -If we go back to our browser and make a request to -, we'll see our text appear on the page. +If you previously stopped the web server to run the controller generator, +restart it with `bin/rails server`. Now visit , +and see our text displayed! ### Setting the Application Home Page -Now that we have made the controller and view, we need to tell Rails when we -want "Hello, Rails!" to show up. In our case, we want it to show up when we -navigate to the root URL of our site, . At the moment, -"Yay! You're on Rails!" is occupying that spot. +At the moment, still displays "Yay! You're on Rails!". +Let's display our "Hello, Rails!" text at as well. To do +so, we will add a route that maps the *root path* of our application to the +appropriate controller and action. -Next, you have to tell Rails where your actual home page is located. - -Open the file `config/routes.rb` in your editor. +Let's open `config/routes.rb`, and add the following `root` route to the top of +the `Rails.application.routes.draw` block: ```ruby Rails.application.routes.draw do - get 'welcome/index' + root "articles#index" - # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html + get "/articles", to: "articles#index" end ``` -This is your application's _routing file_ which holds entries in a special -[DSL (domain-specific language)](https://en.wikipedia.org/wiki/Domain-specific_language) -that tells Rails how to connect incoming requests to -controllers and actions. -Edit this file by adding the line of code `root 'welcome#index'`. -It should look something like the following: +Now we can see our "Hello, Rails!" text when we visit , +confirming that the `root` route is also mapped to the `index` action of +`ArticlesController`. -```ruby -Rails.application.routes.draw do - get 'welcome/index' +TIP: To learn more about routing, see [Rails Routing from the Outside In]( +routing.html). - root 'welcome#index' -end -``` +MVC and You +----------- -`root 'welcome#index'` tells Rails to map requests to the root of the -application to the welcome controller's index action and `get 'welcome/index'` -tells Rails to map requests to to the -welcome controller's index action. This was created earlier when you ran the -controller generator (`bin/rails generate controller Welcome index`). +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. -Launch the web server again if you stopped it to generate the controller (`bin/rails -server`) and navigate to 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 `index` -action and is rendering the view correctly. +Since we have a controller and a view to work with, let's generate the next +piece: a model. -TIP: For more information about routing, refer to [Rails Routing from the Outside In](routing.html). +### Generating a Model -Getting Up and Running ----------------------- +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*. -Now that you've seen how to create a controller, an action, and a view, let's -create something with a bit more substance. - -In the Blog application, you will now create a new _resource_. A resource is the -term used for a collection of similar objects, such as articles, people, or -animals. -You can create, read, update, and destroy items for a resource and these -operations are referred to as _CRUD_ operations. - -Rails provides a `resources` method which can be used to declare a standard REST -resource. You need to add the _article resource_ to the -`config/routes.rb` so the file will look as follows: - -```ruby -Rails.application.routes.draw do - get 'welcome/index' - - resources :articles - - root 'welcome#index' -end -``` - -If you run `bin/rails routes`, you'll see that it has defined routes for all the -standard RESTful actions. The meaning of the prefix column (and other columns) -will be seen later, but for now notice that Rails has inferred the -singular form `article` and makes meaningful use of the distinction. +To define a model, we will use the model generator: ```bash -$ bin/rails routes - Prefix Verb URI Pattern Controller#Action -welcome_index GET /welcome/index(.:format) welcome#index - articles GET /articles(.:format) articles#index - POST /articles(.:format) articles#create - new_article GET /articles/new(.:format) articles#new - edit_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 +$ bin/rails generate model Article title:string body:text ``` -In the next section, you will add the ability to create new articles in your -application and be able to view them. This is the "C" and the "R" from CRUD: -create and read. The form for doing this will look like this: +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(...)`. -![The new article form](images/getting_started/new_article.png) +This will create several files: -It will look a little basic for now, but that's ok. We'll look at improving the -styling for it afterwards. - -### Laying down the Groundwork - -Firstly, you need a place within the application to create a new article. A -great place for that would be at `/articles/new`. With the route already -defined, requests can now be made to `/articles/new` in the application. -Navigate to and you'll see a routing -error: - -![Another routing error, uninitialized constant ArticlesController](images/getting_started/routing_error_no_controller.png) - -This error occurs because the route needs to have a controller defined in order -to serve the request. The solution to this particular problem is to create -a controller called `ArticlesController`. You can do this by running this -command: - -```bash -$ bin/rails generate controller Articles +``` +invoke active_record +create db/migrate/_create_articles.rb +create app/models/article.rb +invoke test_unit +create test/models/article_test.rb +create test/fixtures/articles.yml ``` -If you open up the newly generated `app/controllers/articles_controller.rb` -you'll see a fairly empty controller: +The two files we'll focus on are the migration file +(`db/migrate/_create_articles.rb`) and the model file +(`app/models/article.rb`). -```ruby -class ArticlesController < ApplicationController -end -``` +### Database Migrations -A controller is a class that is defined to inherit from -`ApplicationController`. -It's inside this class that you'll define methods that will become the actions -for this controller. These actions will perform CRUD operations on the articles -within our system. +*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. -NOTE: 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](https://ruby-doc.org/docs/ProgrammingRuby/). - -If you refresh now, you'll get a new error: - -![Unknown action new for ArticlesController!](images/getting_started/unknown_action_new_for_articles.png) - -This error indicates that Rails cannot find the `new` action inside the -`ArticlesController` that you just generated. This is because when controllers -are generated in Rails they are empty by default, unless you tell it -your desired actions during the generation process. - -To manually define an action inside a controller, all you need to do is to -define a new method inside the controller. Open -`app/controllers/articles_controller.rb` and inside the `ArticlesController` -class, define the `new` method so that your controller now looks like this: - -```ruby -class ArticlesController < ApplicationController - def new - end -end -``` - -With the `new` method defined in `ArticlesController`, if you refresh - you'll see another error: - -![Template is missing for articles/new] -(images/getting_started/template_is_missing_articles_new.png) - -You're getting this error now because Rails expects plain actions like this one -to have views associated with them to display their information. With no view -available, Rails will raise an exception. - -Let's look at the full error message again: - ->ArticlesController#new is missing a template for request formats: text/html - ->NOTE! ->Unless told otherwise, Rails expects an action to render a template with the same name, contained in a folder named after its controller. If this controller is an API responding with 204 (No Content), which does not require a template, then this error will occur when trying to access it via browser, since we expect an HTML template to be rendered for such requests. If that's the case, carry on. - -The message identifies which template is missing. In this case, it's the -`articles/new` template. Rails will first look for this template. If not found, -then it will attempt to load a template called `application/new`, because the -`ArticlesController` inherits from `ApplicationController`. - -Next the message contains `request.formats` which specifies the format of -template to be served in response. It is set to `text/html` as we requested -this page via browser, so Rails is looking for an HTML template. - -The simplest template that would work in this case would be one located at -`app/views/articles/new.html.erb`. The extension of this file name is important: -the first extension is the _format_ of the template, and the second extension -is the _handler_ that will be used to render the template. Rails is attempting -to find a template called `articles/new` within `app/views` for the -application. The format for this template can only be `html` and the default -handler for HTML is `erb`. Rails uses other handlers for other formats. -`builder` handler is used to build XML templates and `coffee` handler uses -CoffeeScript to build JavaScript templates. Since you want to create a new -HTML form, you will be using the `ERB` language which is designed to embed Ruby -in HTML. - -Therefore the file should be called `articles/new.html.erb` and needs to 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` and -write this content in it: - -```html -

New Article

-``` - -When you refresh you'll now see that the -page has a title. The route, controller, action, and view are now working -harmoniously! It's time to create the form for a new article. - -### The first form - -To create a form within this template, you will use a *form -builder*. The primary form builder for Rails is provided by a helper -method called `form_with`. To use this method, add this code into -`app/views/articles/new.html.erb`: - -```html+erb -<%= form_with scope: :article, local: true do |form| %> -

- <%= form.label :title %>
- <%= form.text_field :title %> -

- -

- <%= form.label :text %>
- <%= form.text_area :text %> -

- -

- <%= form.submit %> -

-<% end %> -``` - -If you refresh the page now, you'll see the exact same form from our example above. - -When you call `form_with`, you pass it an identifying scope for this -form. In this case, it's the symbol `:article`. This tells the `form_with` -helper what this form is for. Inside the block for this method, the -`FormBuilder` object - represented by `form` - is used to build two labels and two -text fields, one each for the title and text of an article. Finally, a call to -`submit` on the `form` object will create a submit button for the form. - -There's one problem with this form though. If you inspect the HTML that is -generated, by viewing the source of the page, you will see that the `action` -attribute for the form is pointing at `/articles/new`. This is a problem because -this route goes to the very page that you're on right at the moment, and that -route 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_with`. -Typically in Rails, the action that is used for new form submissions -like this is called "create", and so the form should be pointed to that action. - -Edit the `form_with` line inside `app/views/articles/new.html.erb` to look like -this: - -```html+erb -<%= form_with scope: :article, url: articles_path, local: true do |form| %> -``` - -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 of -`bin/rails routes`: - -```bash -$ bin/rails routes - Prefix Verb URI Pattern Controller#Action -welcome_index GET /welcome/index(.:format) welcome#index - articles GET /articles(.:format) articles#index - POST /articles(.:format) articles#create - new_article GET /articles/new(.:format) articles#new - edit_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 Pattern -associated with the `articles` prefix; and the form will (by default) send a -`POST` request to that route. This is associated with the `create` action of -the current controller, the `ArticlesController`. - -With the form and its associated route defined, you will be able to fill in the -form and then click the submit button to begin the process of creating a new -article, so go ahead and do that. When you submit the form, you should see a -familiar error: - -![Unknown action create for ArticlesController] -(images/getting_started/unknown_action_create_for_articles.png) - -You now need to create the `create` action within the `ArticlesController` for -this to work. - -NOTE: By default `form_with` submits forms using Ajax thereby skipping full page -redirects. To make this guide easier to get into we've disabled that with -`local: true` for now. - -### Creating Articles - -To make the "Unknown action" go away, you can define a `create` action within -the `ArticlesController` class in `app/controllers/articles_controller.rb`, -underneath the `new` action, as shown: - -```ruby -class ArticlesController < ApplicationController - def new - end - - def create - end -end -``` - -If you re-submit the form now, you may not see any change on the page. Don't worry! -This is because Rails by default returns `204 No Content` response for an action if -we don't specify what the response should be. We added the `create` action -but didn't specify anything about how the response should be. In this case, the -`create` action should save our new article to the database. - -When a form is submitted, the fields of the form are sent to Rails as -_parameters_. These parameters can then be referenced inside the controller -actions, typically to perform a particular task. To see what these parameters -look like, change the `create` action to this: - -```ruby -def create - render plain: params[:article].inspect -end -``` - -The `render` method here is taking a hash with a key of `:plain` and -value of `params[:article].inspect`. The `params` method is the object which -represents the parameters (or fields) coming in from the form. The `params` -method returns an `ActionController::Parameters` object, which -allows you to access the keys of the hash using either strings or symbols. In -this situation, the only parameters that matter are the ones from the form. - -TIP: 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 see something that looks like the following: - -```ruby -"First Article!", "text"=>"This is my first article."} permitted: false> -``` - -This action is now displaying the parameters for the article that are coming in -from the form. However, this isn't really all that helpful. Yes, you can see the -parameters but nothing in particular is being done with them. - -### Creating the Article Model - -Models in Rails use a singular name, and their corresponding database tables -use a plural name. Rails provides a generator for creating models, which most -Rails developers tend to use when creating new models. To create the new model, -run this command in your terminal: - -```bash -$ bin/rails generate model Article title:string text:text -``` - -With that command we told Rails that we want an `Article` model, together -with a _title_ attribute of type string, and a _text_ attribute -of type text. Those attributes are automatically added to the `articles` -table in the database and mapped to the `Article` model. - -Rails responded by creating a bunch of files. For now, we're only interested -in `app/models/article.rb` and `db/migrate/20140120191729_create_articles.rb` -(your name could be a bit different). The latter is responsible for creating -the database structure, which is what we'll look at next. - -TIP: Active Record is smart enough to automatically map column names to model -attributes, which means you don't have to declare attributes inside Rails -models, as that will be done automatically by Active Record. - -### Running a Migration - -As we've just seen, `bin/rails generate model` created a _database migration_ file -inside the `db/migrate` directory. Migrations are Ruby classes that are -designed to create and modify database tables. Rails uses -rake commands to run migrations, and it's possible to undo a migration after -it's been applied to your database. Migration filenames include a timestamp to -ensure that they're processed in the order that they were created. - -If you look in the `db/migrate/YYYYMMDDHHMMSS_create_articles.rb` file -(remember, yours will have a slightly different name), here's what you'll find: +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 :text + t.text :body t.timestamps end @@ -771,196 +431,213 @@ class CreateArticles < ActiveRecord::Migration[6.0] end ``` -The above migration creates a method named `change` which will be called when -you 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 create -an `articles` table with one string column and a text column. It also creates -two timestamp fields to allow Rails to track article creation and update times. +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. -TIP: For more information about migrations, refer to [Active Record Migrations] -(active_record_migrations.html). +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`). -At this point, you can use a rails command to run the migration: +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 ``` -Rails will execute this migration command and tell you it created the Articles -table. +The command will display output indicating that the table was created: ``` -== CreateArticles: migrating ================================================== +== CreateArticles: migrating =================================== -- create_table(:articles) - -> 0.0019s -== CreateArticles: migrated (0.0020s) ========================================= + -> 0.0018s +== CreateArticles: migrated (0.0018s) ========================== ``` -NOTE. Because you're working in the development environment by default, this -command will apply to the database defined in the `development` section of your -`config/database.yml` file. If you would like to execute migrations in another -environment, for instance in production, you must explicitly pass it when -invoking the command: `bin/rails db:migrate RAILS_ENV=production`. +TIP: To learn more about migrations, see [Active Record Migrations]( +active_record_migrations.html). -### Saving Data in the Controller +Now we can interact with the table using our model. -Back in `ArticlesController`, we need to change the `create` action -to use the new `Article` model to save the data in the database. -Open `app/controllers/articles_controller.rb` and change the `create` action to -look like this: +### Using a Model to Interact with the Database -```ruby -def create - @article = Article.new(params[:article]) +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. - @article.save - redirect_to @article -end +Let's launch the console with this command: + +```bash +$ bin/rails console ``` -Here's what's going on: every Rails model can be initialized with its -respective attributes, which are automatically mapped to the respective -database columns. In the first line we do just that (remember that -`params[: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 should see an `irb` prompt like: -TIP: 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 `app/models/article.rb`. Class names in Ruby must begin with a capital letter. - -TIP: As we'll see later, `@article.save` returns a boolean indicating whether -the article was saved or not. - -If you now go to you'll *almost* be able -to create an article. Try it! You should get an error that looks like this: - -![Forbidden attributes for new article] -(images/getting_started/forbidden_attributes_for_new_article.png) - -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](action_controller_overview.html#strong-parameters), -which requires us to tell Rails exactly which parameters are allowed into our -controller actions. - -Why do you have to bother? The ability to grab and automatically assign all -controller parameters to your model in one shot makes the programmer's job -easier, but this convenience also allows malicious use. What if a request to -the server was crafted to look like a new article form submit but also included -extra fields with values that violated your application's integrity? They would -be 'mass assigned' into your model and then into the database along with the -good stuff - potentially breaking your application or worse. - -We have to define our permitted controller parameters to prevent wrongful mass -assignment. In this case, we want to both allow and require the `title` and -`text` parameters for valid use of `create`. The syntax for this introduces -`require` and `permit`. The change will involve one line in the `create` -action: - -```ruby - @article = Article.new(params.require(:article).permit(:title, :text)) +```irb +Loading development environment (Rails 6.0.2.1) +irb(main):001:0> ``` -This is often factored out into its own method so it can be reused by multiple -actions in the same controller, for example `create` and `update`. Above and -beyond mass assignment issues, the method is often made `private` to make sure -it can't be called outside its intended context. Here is the result: +At this prompt, we can initialize a new `Article` object: -```ruby -def create - @article = Article.new(article_params) - - @article.save - redirect_to @article -end - -private - def article_params - params.require(:article).permit(:title, :text) - end +```irb +irb> article = Article.new(title: "Hello Rails", body: "I am on Rails!") ``` -TIP: For more information, refer to the reference above and -[this blog article about Strong Parameters] -(https://weblog.rubyonrails.org/2012/3/21/strong-parameters/). +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): -### Showing Articles - -If you submit the form again now, Rails will complain about not finding the -`show` action. That's not very useful though, so let's add the `show` action -before proceeding. - -As we have seen in the output of `bin/rails routes`, the route for `show` action is -as follows: - -``` -article GET /articles/:id(.:format) articles#show +```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 special syntax `:id` tells rails that this route expects an `:id` -parameter, which in our case will be the id of the article. +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: -As we did before, we need to add the `show` action in -`app/controllers/articles_controller.rb` and its respective view. +```irb +irb> article +=> #
+``` -NOTE: A frequent practice is to place the standard CRUD actions in each -controller in the following order: `index`, `show`, `new`, `edit`, `create`, `update` -and `destroy`. You may use any order you choose, but keep in mind that these -are public methods; as mentioned earlier in this guide, they must be placed -before declaring `private` visibility in the controller. +The `id`, `created_at`, and `updated_at` attributes of the object are now set. +Rails did this for us when we saved the object. -Given that, let's add the `show` action, as follows: +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) +=> #
+``` + +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 +=> #]> +``` + +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. + +### 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 show - @article = Article.find(params[:id]) + def index + @articles = Article.all end - - def new - end - - # snippet for brevity +end ``` -A couple of things to note. We use `Article.find` to find the article we're -interested in, passing in `params[:id]` to get the `:id` parameter from the -request. We also use an instance variable (prefixed with `@`) to hold a -reference to the article object. We do this because Rails will pass all instance -variables to the view. - -Now, create a new file `app/views/articles/show.html.erb` with the following -content: +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 -

- Title: - <%= @article.title %> -

+

Articles

-

- Text: - <%= @article.text %> -

+
    + <% @articles.each do |article| %> +
  • + <%= article.title %> +
  • + <% end %> +
``` -With this change, you should finally be able to create new articles. -Visit and give it a try! +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. -![Show action for articles](images/getting_started/show_action_for_articles.png) +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 +`<%= %>`. -### Listing all Articles +We can see the final result by visiting . (Remember that +`bin/rails server` must be running!) Here's what happens when we do that: -We still need a way to list all our articles, so let's do that. -The route for this as per output of `bin/rails routes` is: +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. -``` -articles GET /articles(.:format) articles#index +We've connected all the MVC pieces together, and we have our first controller +action! Next, we'll move on to the second action. + +CRUDit Where CRUDit Is Due +-------------------------- + +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. + +### 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 ``` -Add the corresponding `index` action for that route inside the -`ArticlesController` in the `app/controllers/articles_controller.rb` file. -When we write an `index` action, the usual practice is to place it as the -first method in the controller. Let's do it: +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 @@ -971,523 +648,138 @@ class ArticlesController < ApplicationController def show @article = Article.find(params[:id]) end - - def new - end - - # snippet for brevity +end ``` -And then finally, add the view for this action, located at -`app/views/articles/index.html.erb`: +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 -

Listing Articles

+

<%= @article.title %>

- - - - - - +

<%= @article.body %>

+``` +Now we can see the article when we visit ! + +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 +

Articles

+ +
    <% @articles.each do |article| %> -
- - - - +
  • + + <%= article.title %> + +
  • <% end %> -
    TitleText
    <%= article.title %><%= article.text %><%= link_to 'Show', article_path(article) %>
    + ``` -Now if you go to you will see a list of all the -articles that you have created. +### Resourceful Routing -### Adding Links +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. -You can now create, show, and list articles. Now let's add some links to -navigate through pages. - -Open `app/views/welcome/index.html.erb` and modify it as follows: - -```html+erb -

    Hello, Rails!

    -<%= link_to 'My Blog', controller: 'articles' %> -``` - -The `link_to` method is one of Rails' built-in view helpers. It creates a -hyperlink based on text to display and where to go - in this case, to the path -for 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 -`` tag: - -```erb -<%= 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 the -form, to go back to the `index` action: - -```erb -<%= form_with scope: :article, url: articles_path, local: true do |form| %> - ... -<% end %> - -<%= link_to 'Back', articles_path %> -``` - -Finally, add a link to the `app/views/articles/show.html.erb` template to -go back to the `index` action as well, so that people who are viewing a single -article can go back and view the whole list again: - -```html+erb -

    - Title: - <%= @article.title %> -

    - -

    - Text: - <%= @article.text %> -

    - -<%= link_to 'Back', articles_path %> -``` - -TIP: If you want to link to an action in the same controller, you don't need to -specify the `:controller` option, as Rails will use the current controller by -default. - -TIP: In the development environment (which is what you're working in by -default), Rails reloads your application with every browser request, so there's -no need to stop and restart the web server when a change is made. - -### Adding Some Validation - -The model file, `app/models/article.rb` is about as simple as it can get: +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`: ```ruby -class Article < ApplicationRecord +Rails.application.routes.draw do + root "articles#index" + + resources :articles end ``` -There isn't much to this file - but note that the `Article` class inherits from -`ApplicationRecord`. `ApplicationRecord` inherits from `ActiveRecord::Base` -which supplies a great deal of functionality to your Rails models for free, -including basic database CRUD (Create, Read, Update, Destroy) operations, data -validation, as well as sophisticated search support and the ability to relate -multiple models to one another. +We can inspect what routes are mapped by running the `bin/rails routes` command: -Rails includes methods to help you validate the data that you send to models. -Open the `app/models/article.rb` file and edit it: - -```ruby -class Article < ApplicationRecord - validates :title, presence: true, - length: { minimum: 5 } -end +```bash +$ bin/rails routes + 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 ``` -These changes will ensure that all articles have a title that is at least five -characters long. Rails can validate a variety of conditions in a model, -including the presence or uniqueness of columns, their format, and the -existence of associated objects. Validations are covered in detail in [Active -Record Validations](active_record_validations.html). - -With the validation now in place, when you call `@article.save` on an invalid -article, it will return `false`. If you open -`app/controllers/articles_controller.rb` again, you'll notice that we don't -check 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 the -user. To do this, change the `new` and `create` actions inside -`app/controllers/articles_controller.rb` to these: - -```ruby -def new - @article = Article.new -end - -def create - @article = Article.new(article_params) - - if @article.save - redirect_to @article - else - render 'new' - end -end - -private - def article_params - params.require(:article).permit(:title, :text) - end -``` - -The `new` action is now creating a new instance variable called `@article`, and -you'll see why that is in just a few moments. - -Notice that inside the `create` action we use `render` instead of `redirect_to` -when `save` returns `false`. The `render` method is used so that the `@article` -object is passed back to the `new` template when it is rendered. This rendering -is done within the same request as the form submission, whereas the -`redirect_to` will tell the browser to issue another request. - -If you reload - and -try to save an article without a title, Rails will send you back to the -form, but that's not very useful. You need to tell the user that -something went wrong. To do that, you'll modify -`app/views/articles/new.html.erb` to check for error messages: +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 -<%= form_with scope: :article, url: articles_path, local: true do |form| %> - - <% if @article.errors.any? %> -
    -

    - <%= pluralize(@article.errors.count, "error") %> prohibited - this article from being saved: -

    -
      - <% @article.errors.full_messages.each do |msg| %> -
    • <%= msg %>
    • - <% end %> -
    -
    - <% end %> - -

    - <%= form.label :title %>
    - <%= form.text_field :title %> -

    - -

    - <%= form.label :text %>
    - <%= form.text_area :text %> -

    - -

    - <%= form.submit %> -

    - -<% 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 all -errors with `@article.errors.full_messages`. - -`pluralize` is a rails helper that takes a number and a string as its -arguments. If the number is greater than one, the string will be automatically -pluralized. - -The reason why we added `@article = Article.new` in the `ArticlesController` is -that otherwise `@article` would be `nil` in our view, and calling -`@article.errors.any?` would throw an error. - -TIP: Rails automatically wraps fields that contain an error with a div -with class `field_with_errors`. You can define a CSS rule to make them -standout. - -Now you'll get a nice error message when saving an article without a title when -you attempt to do that on the new article form -: - -![Form With Errors](images/getting_started/form_with_errors.png) - -### Updating Articles - -We've covered the "CR" part of CRUD. Now let's focus on the "U" part, updating -articles. - -The first step we'll take is adding an `edit` action to the -`ArticlesController`, generally between the `new` and `create` -actions, as shown: - -```ruby -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 -``` - -NOTE: We're using `edit` to render a view. For the actual -saving of the changes to the Article, we'll add an `update` action later. - - -The view will contain a form similar to the one we used when creating -new articles. Create a file called `app/views/articles/edit.html.erb` and make -it look as follows: - -```html+erb -

    Edit Article

    - -<%= form_with model: @article, local: true do |form| %> - - <% if @article.errors.any? %> -
    -

    - <%= pluralize(@article.errors.count, "error") %> prohibited - this article from being saved: -

    -
      - <% @article.errors.full_messages.each do |msg| %> -
    • <%= msg %>
    • - <% end %> -
    -
    - <% end %> - -

    - <%= form.label :title %>
    - <%= form.text_field :title %> -

    - -

    - <%= form.label :text %>
    - <%= form.text_area :text %> -

    - -

    - <%= form.submit %> -

    - -<% end %> - -<%= link_to 'Back', articles_path %> -``` - -This time we point the form to the `update` action, which is not defined yet -but will be very soon. - -Passing the article object to the `form_with` method will automatically set the URL for -submitting the edited article form. This option tells Rails that we want this -form to be submitted via the `PATCH` HTTP method, which is the HTTP method you're -expected to use to **update** resources according to the REST protocol. - -Also, passing a model object to `form_with`, like `model: @article` in the edit -view above, will cause form helpers to fill in form fields with the corresponding -values of the object. Passing in a symbol scope such as `scope: :article`, as -was done in the new view, only creates empty form fields. -More details can be found in [form_with documentation] -(https://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html#method-i-form_with). - -Next, we need to create the `update` action in -`app/controllers/articles_controller.rb`. -Add it between the `create` action and the `private` method: - -```ruby -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 - -private - def article_params - params.require(:article).permit(:title, :text) - end -``` - -The new method, `update`, is used when you want to update a record -that already exists, and it accepts a hash containing the attributes -that you want to update. As before, if there was an error updating the -article we want to show the form back to the user. - -We reuse the `article_params` method that we defined earlier for the create -action. - -TIP: It is not necessary to pass all the attributes to `update`. For example, -if `@article.update(title: 'A new title')` was called, Rails would only update -the `title` attribute, leaving all other attributes untouched. - -Finally, we want to show a link to the `edit` action in the list of all the -articles, so let's add that now to `app/views/articles/index.html.erb` to make -it appear next to the "Show" link: - -```html+erb -
    - - - - - +

    Articles

    +
      <% @articles.each do |article| %> -
    - - - - - +
  • + + <%= article.title %> + +
  • <% end %> -
    TitleText
    <%= article.title %><%= article.text %><%= link_to 'Show', article_path(article) %><%= link_to 'Edit', edit_article_path(article) %>
    + ``` -And we'll also add one to the `app/views/articles/show.html.erb` template as -well, so that there's also an "Edit" link on an article's page. Add this at the -bottom of the template: +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 -... +

    Articles

    -<%= link_to 'Edit', edit_article_path(@article) %> | -<%= link_to 'Back', articles_path %> -``` - -And here's how our app looks so far: - -![Index action with edit link](images/getting_started/index_action_with_edit_link.png) - -### Using partials to clean up duplication in views - -Our `edit` page looks very similar to the `new` page; in fact, they -both share the same code for displaying the form. Let's remove this -duplication by using a view partial. By convention, partial files are -prefixed with an underscore. - -TIP: You can read more about partials in the -[Layouts and Rendering in Rails](layouts_and_rendering.html) guide. - -Create a new file `app/views/articles/_form.html.erb` with the following -content: - -```html+erb -<%= form_with model: @article, local: true do |form| %> - - <% if @article.errors.any? %> -
    -

    - <%= pluralize(@article.errors.count, "error") %> prohibited - this article from being saved: -

    -
      - <% @article.errors.full_messages.each do |msg| %> -
    • <%= msg %>
    • - <% end %> -
    -
    +
      + <% @articles.each do |article| %> +
    • + <%= link_to article.title, article %> +
    • <% end %> - -

      - <%= form.label :title %>
      - <%= form.text_field :title %> -

      - -

      - <%= form.label :text %>
      - <%= form.text_area :text %> -

      - -

      - <%= form.submit %> -

      - -<% end %> +
    ``` -Everything except for the `form_with` declaration remained the same. -The reason we can use this shorter `form_with` declaration -to stand in for either of the other forms is that `@article` is a *resource* -corresponding to a full set of RESTful routes, and Rails is able to infer -which URI and method to use. -For more information about this use of `form_with`, see [Resource-oriented style] -(https://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html#method-i-form_with-label-Resource-oriented+style). +Nice! -Now, let's update the `app/views/articles/new.html.erb` view to use this new -partial, rewriting it completely: +TIP: To learn more about routing, see [Rails Routing from the Outside In]( +routing.html). -```html+erb -

    New Article

    +### Creating a New Article -<%= render 'form' %> +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. -<%= link_to 'Back', articles_path %> -``` - -Then do the same for the `app/views/articles/edit.html.erb` view: - -```html+erb -

    Edit Article

    - -<%= render 'form' %> - -<%= link_to 'Back', articles_path %> -``` - -### Deleting Articles - -We're now ready to cover the "D" part of CRUD, deleting articles from the -database. Following the REST convention, the route for -deleting articles as per output of `bin/rails routes` is: - -```ruby -DELETE /articles/:id(.:format) articles#destroy -``` - -The `delete` routing method should be used for routes that destroy -resources. If this was left as a typical `get` route, it could be possible for -people to craft malicious URLs like this: - -```html -look at this cat! -``` - -We use the `delete` method for destroying resources, and this route is mapped -to the `destroy` action inside `app/controllers/articles_controller.rb`, which -doesn't exist yet. The `destroy` method is generally the last CRUD action in -the controller, and like the other public CRUD actions, it must be placed -before any `private` or `protected` methods. Let's add it: - -```ruby -def destroy - @article = Article.find(params[:id]) - @article.destroy - - redirect_to articles_path -end -``` - -The complete `ArticlesController` in the -`app/controllers/articles_controller.rb` file should now look like this: +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: ```ruby class ArticlesController < ApplicationController @@ -1503,27 +795,470 @@ class ArticlesController < ApplicationController @article = Article.new end - def edit + def create + @article = Article.new(title: "...", body: "...") + + if @article.save + redirect_to @article + else + render :new + end + end +end +``` + +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. + +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. + +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. + +#### Using a Form Builder + +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: + +```html+erb +

    New Article

    + +<%= form_with model: @article, local: true do |form| %> +
    + <%= form.label :title %>
    + <%= form.text_field :title %> +
    + +
    + <%= form.label :body %>
    + <%= form.text_area :body %> +
    + +
    + <%= form.submit %> +
    +<% end %> +``` + +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. + +NOTE: By default, `form_with` creates a form that submits via Ajax to avoid full +page reloads. To make this guide easier to follow, we have disabled that feature +by using `local: true` in the above code. + +The resulting output from our `form_with` call will look like: + +```html +
    + + +
    +
    + +
    + +
    +
    + +
    + +
    + +
    +
    +``` + +TIP: To learn more about form builders, see [Action View Form Helpers]( +form_helpers.html). + +#### 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: + +```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 - render 'new' + render :new end end + private + def article_params + params.require(:article).permit(:title, :body) + end +end +``` + +TIP: To learn more about Strong Parameters, see [Action Controller Overview § +Strong Parameters](action_controller_overview.html#strong-parameters). + +#### Validations and Displaying Error Messages + +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. + +Let's add some validations to our model in `app/models/article.rb`: + +```ruby +class Article < ApplicationRecord + validates :title, presence: true + validates :body, presence: true, length: { minimum: 10 } +end +``` + +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. + +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. + +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. + +With our validations in place, let's modify `app/views/articles/new.html.erb` to +display any error messages for `title` and `body`: + +```html+erb +

    New Article

    + +<%= form_with model: @article, local: true do |form| %> +
    + <%= form.label :title %>
    + <%= form.text_field :title %> + <%= @article.errors.full_messages_for(:title).each do |message| %> +
    <%= message %>
    + <% end %> +
    + +
    + <%= form.label :body %>
    + <%= form.text_area :body %>
    + <%= @article.errors.full_messages_for(:body).each do |message| %> +
    <%= message %>
    + <% end %> +
    + +
    + <%= form.submit %> +
    +<% end %> +``` + +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. + +To understand how all of this works together, let's take another look at the +`new` and `create` controller actions: + +```ruby + def new + @article = Article.new + end + + def create + @article = Article.new(article_params) + + if @article.save + redirect_to @article + else + render :new + end + end +``` + +When we visit , 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). + +#### Finishing Up + +We can now create an article by visiting . +To finish up, let's link to that page from the bottom of +`app/views/articles/index.html.erb`: + +```html+erb +

    Articles

    + +
      + <% @articles.each do |article| %> +
    • + <%= link_to article.title, article %> +
    • + <% end %> +
    + +<%= link_to "New Article", new_article_path %> +``` + +### Updating an Article + +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. + +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: + +```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 + render :new + end + end + + def edit + @article = Article.find(params[:id]) + end + def update @article = Article.find(params[:id]) if @article.update(article_params) redirect_to @article else - render 'edit' + render :edit + end + end + + private + def article_params + params.require(:article).permit(:title, :body) + end +end +``` + +Notice how the `edit` and `update` actions resemble the `new` and `create` +actions. + +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`. + +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`. + +#### Using Partials to Share View Code + +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. + +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: + +```html+erb +<%= form_with model: article, local: true do |form| %> +
    + <%= form.label :title %>
    + <%= form.text_field :title %> + <%= article.errors.full_messages_for(:title).each do |message| %> +
    <%= message %>
    + <% end %> +
    + +
    + <%= form.label :body %>
    + <%= form.text_area :body %>
    + <%= article.errors.full_messages_for(:body).each do |message| %> +
    <%= message %>
    + <% end %> +
    + +
    + <%= form.submit %> +
    +<% end %> +``` + +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. + +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): + +```html+erb +

    New Article

    + +<%= render "form", article: @article %> +``` + +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`: + +```html+erb +

    Edit Article

    + +<%= render "form", article: @article %> +``` + +TIP: To learn more about partials, see [Layouts and Rendering in Rails § Using +Partials](layouts_and_rendering.html#using-partials). + +#### Finishing Up + +We can now update an article by visiting its edit page, e.g. +. To finish up, let's link to the edit +page from the bottom of `app/views/articles/show.html.erb`: + +```html+erb +

    <%= @article.title %>

    + +

    <%= @article.body %>

    + +
      +
    • <%= link_to "Edit", edit_article_path(@article) %>
    • +
    +``` + +### Deleting an Article + +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`. + +So, let's add a typical `destroy` action to `app/controllers/articles_controller.rb`, +below the `update` action: + +```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 + render :new + end + end + + def edit + @article = Article.find(params[:id]) + end + + def update + @article = Article.find(params[:id]) + + if @article.update(article_params) + redirect_to @article + else + render :edit end end @@ -1531,68 +1266,53 @@ class ArticlesController < ApplicationController @article = Article.find(params[:id]) @article.destroy - redirect_to articles_path + redirect_to root_path end private def article_params - params.require(:article).permit(:title, :text) + params.require(:article).permit(:title, :body) end end ``` -You can call `destroy` on Active Record objects when you want to delete -them from the database. Note that we don't need to add a view for this -action since we're redirecting to the `index` action. +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. -Finally, add a 'Destroy' link to your `index` action template -(`app/views/articles/index.html.erb`) to wrap everything together. +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`. + +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: ```html+erb -

    Listing Articles

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

    <%= @article.title %>

    - <% @articles.each do |article| %> - - - - - - - - <% end %> -
    TitleText
    <%= article.title %><%= article.text %><%= link_to 'Show', article_path(article) %><%= link_to 'Edit', edit_article_path(article) %><%= link_to 'Destroy', article_path(article), - method: :delete, - data: { confirm: 'Are you sure?' } %>
    +

    <%= @article.body %>

    + +
      +
    • <%= link_to "Edit", edit_article_path(@article) %>
    • +
    • <%= link_to "Destroy", article_path(@article), + method: :delete, + data: { confirm: "Are you sure?" } %>
    • +
    ``` -Here we're using `link_to` in a different way. We pass the named route as the -second argument, and then the options as another argument. The `method: :delete` -and `data: { confirm: 'Are you sure?' }` options are used as HTML5 attributes so -that when the link is clicked, Rails will first show a confirm dialog to the -user, and then submit the link with method `delete`. This is done via the -JavaScript file `rails-ujs` which is automatically included in your -application's layout (`app/views/layouts/application.html.erb`) when you -generated the application. Without this file, the confirmation dialog box won't -appear. +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. -![Confirm Dialog](images/getting_started/confirm_dialog.png) +TIP: To learn more about Unobtrusive JavaScript, see [Working With JavaScript in +Rails](working_with_javascript_in_rails.html). -TIP: Learn more about Unobtrusive JavaScript on -[Working With JavaScript in Rails](working_with_javascript_in_rails.html) guide. - -Congratulations, you can now create, show, list, update, and destroy -articles. - -TIP: In general, Rails encourages using resources objects instead of -declaring routes manually. For more information about routing, see -[Rails Routing from the Outside In](routing.html). +And that's it! We can now list, show, create, update, and delete articles! +InCRUDable! Adding a Second Model --------------------- @@ -1696,8 +1416,9 @@ association: ```ruby class Article < ApplicationRecord has_many :comments - validates :title, presence: true, - length: { minimum: 5 } + + validates :title, presence: true + validates :body, presence: true, length: { minimum: 10 } end ``` @@ -1716,8 +1437,12 @@ knows where we would like to navigate to see `comments`. Open up the `config/routes.rb` file again, and edit it as follows: ```ruby -resources :articles do - resources :comments +Rails.application.routes.draw do + root "articles#index" + + resources :articles do + resources :comments + end end ``` @@ -1757,15 +1482,16 @@ So first, we'll wire up the Article show template (`app/views/articles/show.html.erb`) to let us make a new comment: ```html+erb -

    - Title: - <%= @article.title %> -

    +

    <%= @article.title %>

    -

    - Text: - <%= @article.text %> -

    +

    <%= @article.body %>

    + +
      +
    • <%= link_to "Edit", edit_article_path(@article) %>
    • +
    • <%= link_to "Destroy", article_path(@article), + method: :delete, + data: { confirm: "Are you sure?" } %>
    • +

    Add a comment:

    <%= form_with model: [ @article, @article.comments.build ], local: true do |form| %> @@ -1781,9 +1507,6 @@ So first, we'll wire up the Article show template <%= form.submit %>

    <% 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 by @@ -1825,15 +1548,16 @@ the `show` action of the `ArticlesController` which in turn renders the add that to the `app/views/articles/show.html.erb`. ```html+erb -

    - Title: - <%= @article.title %> -

    +

    <%= @article.title %>

    -

    - Text: - <%= @article.text %> -

    +

    <%= @article.body %>

    + +
      +
    • <%= link_to "Edit", edit_article_path(@article) %>
    • +
    • <%= link_to "Destroy", article_path(@article), + method: :delete, + data: { confirm: "Are you sure?" } %>
    • +

    Comments

    <% @article.comments.each do |comment| %> @@ -1862,9 +1586,6 @@ add that to the `app/views/articles/show.html.erb`. <%= form.submit %>

    <% 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 the @@ -1901,15 +1622,16 @@ Then you can change `app/views/articles/show.html.erb` to look like the following: ```html+erb -

    - Title: - <%= @article.title %> -

    +

    <%= @article.title %>

    -

    - Text: - <%= @article.text %> -

    +

    <%= @article.body %>

    + +
      +
    • <%= link_to "Edit", edit_article_path(@article) %>
    • +
    • <%= link_to "Destroy", article_path(@article), + method: :delete, + data: { confirm: "Are you sure?" } %>
    • +

    Comments

    <%= render @article.comments %> @@ -1928,9 +1650,6 @@ following: <%= form.submit %>

    <% 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` once @@ -1963,24 +1682,22 @@ create a file `app/views/comments/_form.html.erb` containing: Then you make the `app/views/articles/show.html.erb` look like the following: ```html+erb -

    - Title: - <%= @article.title %> -

    +

    <%= @article.title %>

    -

    - Text: - <%= @article.text %> -

    +

    <%= @article.body %>

    + +
      +
    • <%= link_to "Edit", edit_article_path(@article) %>
    • +
    • <%= link_to "Destroy", article_path(@article), + method: :delete, + data: { confirm: "Are you sure?" } %>
    • +

    Comments

    <%= render @article.comments %>

    Add a comment:

    <%= 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, @@ -2010,8 +1727,9 @@ Within the `article` model, after running a migration to add a `status` column, ```ruby class Article < ApplicationRecord has_many :comments - validates :title, presence: true, - length: { minimum: 5 } + + validates :title, presence: true + validates :body, presence: true, length: { minimum: 10 } VALID_STATUSES = ['public', 'private', 'archived'] @@ -2042,29 +1760,19 @@ 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 -

    Listing Articles

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

    Articles

    +
      <% @articles.each do |article| %> <% unless article.archived? %> -
    - - - - - - +
  • + <%= link_to article.title, article %> +
  • <% end %> <% end %> -
    TitleText
    <%= article.title %><%= article.text %><%= link_to 'Show', article_path(article) %><%= link_to 'Edit', edit_article_path(article) %><%= link_to 'Destroy', article_path(article), - method: :delete, - data: { confirm: 'Are you sure?' } %>
    + + +<%= link_to "New Article", new_article_path %> ``` 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. @@ -2109,9 +1817,8 @@ class Article < ApplicationRecord include Visible has_many :comments - validates :title, presence: true, - length: { minimum: 5 } - + validates :title, presence: true + validates :body, presence: true, length: { minimum: 10 } end ``` @@ -2151,30 +1858,19 @@ end Then in the view, you can call it like any class method: ```html+erb -

    Listing Articles

    -Our blog has <%= Article.public_count %> articles and counting! Add yours now. -<%= link_to 'New article', new_article_path %> - - - - - - +

    Articles

    +Our blog has <%= Article.public_count %> articles and counting! + +
      <% @articles.each do |article| %> - <% unless article.archived? %> -
    - - - - - - - <% end %> +
  • + <%= link_to article.title, article %> +
  • <% end %> -
    TitleText
    <%= article.title %><%= article.text %><%= link_to 'Show', article_path(article) %><%= link_to 'Edit', edit_article_path(article) %><%= link_to 'Destroy', article_path(article), - method: :delete, - data: { confirm: 'Are you sure?' } %>
    + + +<%= link_to "New Article", new_article_path %> ``` Deleting Comments @@ -2201,7 +1897,7 @@ So first, let's add the delete link in the

    <%= link_to 'Destroy Comment', [comment.article, comment], method: :delete, - data: { confirm: 'Are you sure?' } %> + data: { confirm: "Are you sure?" } %>

    ``` @@ -2249,8 +1945,9 @@ class Article < ApplicationRecord include Visible has_many :comments, dependent: :destroy - validates :title, presence: true, - length: { minimum: 5 } + + validates :title, presence: true + validates :body, presence: true, length: { minimum: 10 } end ```