Series hướng dẫn lập trình ruby on rails phần 2

This guide is designed for beginners who want to get started with creating a Rails application from scratch. It does not assume that you have any prior experience with Rails.

Show

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

    • Official Ruby Programming Language website

    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.

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

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

    The Rails philosophy includes two major guiding principles:

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

    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.

    By following along with this guide, you'll create a Rails project called

    require "application_controller" # DON'T DO THIS.
    

    9, a (very) simple weblog. Before you can start building the application, you need to make sure that you have Rails itself installed.

    The examples below use

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

    0 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

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

    1.

    Before you install Rails, you should check to make sure that your system has the proper prerequisites installed. These include:

    • Ruby
    • SQLite3

    Open up a command line prompt. On macOS open Terminal.app; on Windows choose "Run" from your Start menu and type

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

    2. Any commands prefaced with a dollar sign

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

    0 should be run in the command line. Verify that you have a current version of Ruby installed:

    $ ruby --version
    ruby 2.7.0
    

    Rails requires Ruby version 2.7.0 or later. It is preferred to use the latest Ruby version. If the version number returned is less than that number (such as 2.3.7, or 1.8.7), you'll need to install a fresh copy of Ruby.

    To install Rails on Windows, you'll first need to install Ruby Installer.

    For more installation methods for most Operating Systems take a look at ruby-lang.org.

    You will also need an installation of the SQLite3 database. Many popular UNIX-like OSes ship with an acceptable version of SQLite3. Others can find installation instructions at the SQLite3 website.

    Verify that it is correctly installed and in your load

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

    4:

    The program should report its version.

    To install Rails, use the

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

    5 command provided by RubyGems:

    To verify that you have everything installed correctly, you should be able to run the following in a new terminal:

    $ rails --version
    Rails 7.1.0
    

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

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

    To use this generator, open a terminal, navigate to a directory where you have rights to create files, and run:

    This will create a Rails application called Blog in a

    require "application_controller" # DON'T DO THIS.
    

    9 directory and install the gem dependencies that are already mentioned in

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

    7 using

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

    8.

    You can see all of the command line options that the Rails application generator accepts by running

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

    9.

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

    The

    require "application_controller" # DON'T DO THIS.
    

    9 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

    invoke  active_record
    create    db/migrate/<timestamp>_create_articles.rb
    create    app/models/article.rb
    invoke    test_unit
    create      test/models/article_test.rb
    create      test/fixtures/articles.yml
    

    1 folder, but here's a basic rundown on the function of each 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

    invoke  active_record
    create    db/migrate/<timestamp>_create_articles.rb
    create    app/models/article.rb
    invoke    test_unit
    create      test/models/article_test.rb
    create      test/fixtures/articles.yml
    

    2 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. config.ru Rack configuration for Rack-based servers used to start the application. For more information about Rack, see the Rack website. db/ Contains your current database schema, as well as the database migrations. Gemfile Gemfile.lock These files allow you to specify what gem dependencies are needed for your Rails application. These files are used by the Bundler gem. For more information about Bundler, see the Bundler website. lib/ Extended modules for your application. log/ Application log files. public/ 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

    invoke  active_record
    create    db/migrate/<timestamp>_create_articles.rb
    create    app/models/article.rb
    invoke    test_unit
    create      test/models/article_test.rb
    create      test/fixtures/articles.yml
    

    3, you should add your own tasks by adding files to the

    invoke  active_record
    create    db/migrate/<timestamp>_create_articles.rb
    create    app/models/article.rb
    invoke    test_unit
    create      test/models/article_test.rb
    create      test/fixtures/articles.yml
    

    4 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. test/ Unit tests, fixtures, and other test apparatus. These are covered in Testing Rails Applications. 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. .gitattributes This file defines metadata for specific paths in a git repository. This metadata can be used by git and other tools to enhance their behavior. See the gitattributes documentation for more information. .gitignore This file tells git which files (or patterns) it should ignore. See GitHub - Ignoring files for more information about ignoring files. .ruby-version This file contains the default Ruby version.

    To begin with, let's get some text up on screen quickly. To do this, you need to 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 command in the

    require "application_controller" # DON'T DO THIS.
    

    9 directory:

    If you are using Windows, you have to pass the scripts under the

    invoke  active_record
    create    db/migrate/<timestamp>_create_articles.rb
    create    app/models/article.rb
    invoke    test_unit
    create      test/models/article_test.rb
    create      test/fixtures/articles.yml
    

    6 folder directly to the Ruby interpreter e.g.

    invoke  active_record
    create    db/migrate/<timestamp>_create_articles.rb
    create    app/models/article.rb
    invoke    test_unit
    create      test/models/article_test.rb
    create      test/fixtures/articles.yml
    

    7.

    JavaScript asset compression requires you have a JavaScript runtime available on your system, in the absence of a runtime you will see an

    invoke  active_record
    create    db/migrate/<timestamp>_create_articles.rb
    create    app/models/article.rb
    invoke    test_unit
    create      test/models/article_test.rb
    create      test/fixtures/articles.yml
    

    8 error during asset compression. Usually macOS and Windows come with a JavaScript runtime installed.

    invoke  active_record
    create    db/migrate/<timestamp>_create_articles.rb
    create    app/models/article.rb
    invoke    test_unit
    create      test/models/article_test.rb
    create      test/fixtures/articles.yml
    

    9 is the recommended runtime for JRuby users and is added by default to the

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

    7 in apps generated under JRuby. You can investigate all the supported runtimes at .

    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 http://localhost:3000. You should see the Rails default information page:

    Series hướng dẫn lập trình ruby on rails phần 2

    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.

    The Rails startup page is the smoke test for a new Rails application: it makes sure that you have your software configured correctly enough to serve a page.

    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.

    In terms of implementation: Routes are rules written in a Ruby DSL (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.

    Let's start by adding a route to our routes file,

    $ rails --version
    Rails 7.1.0
    

    01, at the top of the

    $ rails --version
    Rails 7.1.0
    

    02 block:

    Rails.application.routes.draw do
      get "/articles", to: "articles
    # index"
      # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
    end
    

    The route above declares that

    $ rails --version
    Rails 7.1.0
    

    03 requests are mapped to the

    $ rails --version
    Rails 7.1.0
    

    04 action of

    $ rails --version
    Rails 7.1.0
    

    05.

    To create

    $ rails --version
    Rails 7.1.0
    

    05 and its

    $ rails --version
    Rails 7.1.0
    

    04 action, we'll run the controller generator (with the

    $ rails --version
    Rails 7.1.0
    

    08 option because we already have an appropriate route):

    $ bin/rails generate controller Articles index --skip-routes
    

    Rails will create several files for you:

    create  app/controllers/articles_controller.rb
    invoke  erb
    create    app/views/articles
    create    app/views/articles/index.html.erb
    invoke  test_unit
    create    test/controllers/articles_controller_test.rb
    invoke  helper
    create    app/helpers/articles_helper.rb
    invoke    test_unit
    

    The most important of these is the controller file,

    $ rails --version
    Rails 7.1.0
    

    09. Let's take a look at it:

    class ArticlesController < ApplicationController
      def index
      end
    end
    

    The

    $ rails --version
    Rails 7.1.0
    

    04 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

    $ rails --version
    Rails 7.1.0
    

    11 directory. So the

    $ rails --version
    Rails 7.1.0
    

    04 action will render

    $ rails --version
    Rails 7.1.0
    

    13 by default.

    Let's open

    $ rails --version
    Rails 7.1.0
    

    13, and replace its contents with:

    If you previously stopped the web server to run the controller generator, restart it with

    $ rails --version
    Rails 7.1.0
    

    15. Now visit http://localhost:3000/articles, and see our text displayed!

    At the moment, http://localhost:3000 still displays a page with the Ruby on Rails logo. Let's display our "Hello, Rails!" text at http://localhost:3000 as well. To do so, we will add a route that maps the root path of our application to the appropriate controller and action.

    Let's open

    $ rails --version
    Rails 7.1.0
    

    01, and add the following

    $ rails --version
    Rails 7.1.0
    

    17 route to the top of the

    $ rails --version
    Rails 7.1.0
    

    02 block:

    Rails.application.routes.draw do
      root "articles
    # index"
      get "/articles", to: "articles
    # index"
    end
    

    Now we can see our "Hello, Rails!" text when we visit http://localhost:3000, confirming that the

    $ rails --version
    Rails 7.1.0
    

    17 route is also mapped to the

    $ rails --version
    Rails 7.1.0
    

    04 action of

    $ rails --version
    Rails 7.1.0
    

    05.

    Rails applications do not use

    $ rails --version
    Rails 7.1.0
    

    22 to load application code.

    You may have noticed that

    $ rails --version
    Rails 7.1.0
    

    05 inherits from

    $ rails --version
    Rails 7.1.0
    

    24, but

    $ rails --version
    Rails 7.1.0
    

    09 does not have anything like

    require "application_controller" # DON'T DO THIS.
    

    Application classes and modules are available everywhere, you do not need and should not load anything under

    invoke  active_record
    create    db/migrate/<timestamp>_create_articles.rb
    create    app/models/article.rb
    invoke    test_unit
    create      test/models/article_test.rb
    create      test/fixtures/articles.yml
    

    1 with

    $ rails --version
    Rails 7.1.0
    

    22. This feature is called autoloading, and you can learn more about it in Autoloading and Reloading Constants.

    You only need

    $ rails --version
    Rails 7.1.0
    

    22 calls for two use cases:

    • To load files under the

      $ rails --version Rails 7.1.0

      29 directory.
    • To load gem dependencies that have

      $ rails --version Rails 7.1.0

      30 in the

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

      7.

    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) pattern. MVC is a design pattern that divides the responsibilities of an application to make it easier to reason about. Rails follows this design pattern by convention.

    Since we have a controller and a view to work with, let's generate the next piece: a model.

    A model is a Ruby class that is used to represent data. Additionally, models can interact with the application's database through a feature of Rails called Active Record.

    To define a model, we will use the model generator:

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

    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

    $ rails --version
    Rails 7.1.0
    

    32, not

    $ rails --version
    Rails 7.1.0
    

    33.

    This will create several files:

    invoke  active_record
    create    db/migrate/<timestamp>_create_articles.rb
    create    app/models/article.rb
    invoke    test_unit
    create      test/models/article_test.rb
    create      test/fixtures/articles.yml
    

    The two files we'll focus on are the migration file (

    $ rails --version
    Rails 7.1.0
    

    1. and the model file (

    $ rails --version
    Rails 7.1.0
    

    35).

    Migrations are used to alter the structure of an application's database. In Rails applications, migrations are written in Ruby so that they can be database-agnostic.

    Let's take a look at the contents of our new migration file:

    $ rails --version
    Rails 7.1.0
    

    0

    The call to

    $ rails --version
    Rails 7.1.0
    

    36 specifies how the

    $ rails --version
    Rails 7.1.0
    

    37 table should be constructed. By default, the

    $ rails --version
    Rails 7.1.0
    

    36 method adds an

    $ rails --version
    Rails 7.1.0
    

    39 column as an auto-incrementing primary key. So the first record in the table will have an

    $ rails --version
    Rails 7.1.0
    

    39 of 1, the next record will have an

    $ rails --version
    Rails 7.1.0
    

    39 of 2, and so on.

    Inside the block for

    $ rails --version
    Rails 7.1.0
    

    36, two columns are defined:

    $ rails --version
    Rails 7.1.0
    

    43 and

    $ rails --version
    Rails 7.1.0
    

    44. These were added by the generator because we included them in our generate command (

    $ rails --version
    Rails 7.1.0
    

    45).

    On the last line of the block is a call to

    $ rails --version
    Rails 7.1.0
    

    46. This method defines two additional columns named

    $ rails --version
    Rails 7.1.0
    

    47 and

    $ rails --version
    Rails 7.1.0
    

    48. 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:

    The command will display output indicating that the table was created:

    $ rails --version
    Rails 7.1.0
    

    1

    Now we can interact with the table using our model.

    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

    $ rails --version
    Rails 7.1.0
    

    49, but it also automatically loads Rails and our application code.

    Let's launch the console with this command:

    You should see an

    $ rails --version
    Rails 7.1.0
    

    49 prompt like:

    $ rails --version
    Rails 7.1.0
    

    2

    At this prompt, we can initialize a new

    $ rails --version
    Rails 7.1.0
    

    51 object:

    $ rails --version
    Rails 7.1.0
    

    3

    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 :

    $ rails --version
    Rails 7.1.0
    

    4

    The above output shows an

    $ rails --version
    Rails 7.1.0
    

    53 database query. This indicates that the article has been inserted into our table. And if we take a look at the

    $ rails --version
    Rails 7.1.0
    

    54 object again, we see something interesting has happened:

    $ rails --version
    Rails 7.1.0
    

    5

    The

    $ rails --version
    Rails 7.1.0
    

    39,

    $ rails --version
    Rails 7.1.0
    

    47, and

    $ rails --version
    Rails 7.1.0
    

    48 attributes of the object are now set. Rails did this for us when we saved the object.

    When we want to fetch this article from the database, we can call on the model and pass the

    $ rails --version
    Rails 7.1.0
    

    39 as an argument:

    $ rails --version
    Rails 7.1.0
    

    6

    And when we want to fetch all articles from the database, we can call on the model:

    $ rails --version
    Rails 7.1.0
    

    7

    This method returns an

    $ rails --version
    Rails 7.1.0
    

    61 object, which you can think of as a super-powered array.

    Models are the final piece of the MVC puzzle. Next, we will connect all of the pieces together.

    Let's go back to our controller in

    $ rails --version
    Rails 7.1.0
    

    09, and change the

    $ rails --version
    Rails 7.1.0
    

    04 action to fetch all articles from the database:

    $ rails --version
    Rails 7.1.0
    

    8

    Controller instance variables can be accessed by the view. That means we can reference

    $ rails --version
    Rails 7.1.0
    

    64 in

    $ rails --version
    Rails 7.1.0
    

    13. Let's open that file, and replace its contents with:

    $ rails --version
    Rails 7.1.0
    

    9

    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:

    $ rails --version
    Rails 7.1.0
    

    66 and

    $ rails --version
    Rails 7.1.0
    

    67. The

    $ rails --version
    Rails 7.1.0
    

    66 tag means "evaluate the enclosed Ruby code." The

    $ rails --version
    Rails 7.1.0
    

    67 tag means "evaluate the enclosed Ruby code, and output the value it returns." Anything you could write in a regular Ruby program can go inside these ERB tags, though it's usually best to keep the contents of ERB tags short, for readability.

    Since we don't want to output the value returned by

    $ rails --version
    Rails 7.1.0
    

    70, we've enclosed that code in

    $ rails --version
    Rails 7.1.0
    

    66. But, since we do want to output the value returned by

    $ rails --version
    Rails 7.1.0
    

    72 (for each article), we've enclosed that code in

    $ rails --version
    Rails 7.1.0
    

    67.

    We can see the final result by visiting http://localhost:3000. (Remember that

    $ rails --version
    Rails 7.1.0
    

    15 must be running!) Here's what happens when we do that:

    1. The browser makes a request:

      $ rails --version Rails 7.1.0

      75.
    2. Our Rails application receives this request.
    3. The Rails router maps the root route to the

      $ rails --version Rails 7.1.0

      04 action of

      $ rails --version Rails 7.1.0

      05.
    4. The

      $ rails --version Rails 7.1.0

      04 action uses the

      $ rails --version Rails 7.1.0

      51 model to fetch all articles in the database.
    5. Rails automatically renders the

      $ rails --version Rails 7.1.0

      13 view.
    6. The ERB code in the view is evaluated to output HTML.
    7. The server sends a response containing the HTML back to the browser.

    We've connected all the MVC pieces together, and we have our first controller action! Next, we'll move on to the second action.

    Almost all web applications involve CRUD (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.

    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

    $ rails --version
    Rails 7.1.0
    

    01, and insert the last route shown here:

    Rails.application.routes.draw do
      get "/articles", to: "articles
    # index"
      # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
    end
    

    0

    The new route is another

    $ rails --version
    Rails 7.1.0
    

    82 route, but it has something extra in its path:

    $ rails --version
    Rails 7.1.0
    

    83. This designates a route parameter. A route parameter captures a segment of the request's path, and puts that value into the

    $ rails --version
    Rails 7.1.0
    

    84 Hash, which is accessible by the controller action. For example, when handling a request like

    $ rails --version
    Rails 7.1.0
    

    85,

    $ rails --version
    Rails 7.1.0
    

    86 would be captured as the value for

    $ rails --version
    Rails 7.1.0
    

    83, which would then be accessible as

    $ rails --version
    Rails 7.1.0
    

    88 in the

    $ rails --version
    Rails 7.1.0
    

    89 action of

    $ rails --version
    Rails 7.1.0
    

    05.

    Let's add that

    $ rails --version
    Rails 7.1.0
    

    89 action now, below the

    $ rails --version
    Rails 7.1.0
    

    04 action in

    $ rails --version
    Rails 7.1.0
    

    09:

    Rails.application.routes.draw do
      get "/articles", to: "articles
    # index"
      # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
    end
    

    1

    The

    $ rails --version
    Rails 7.1.0
    

    89 action calls

    $ rails --version
    Rails 7.1.0
    

    95 () with the ID captured by the route parameter. The returned article is stored in the

    $ rails --version
    Rails 7.1.0
    

    96 instance variable, so it is accessible by the view. By default, the

    $ rails --version
    Rails 7.1.0
    

    89 action will render

    $ rails --version
    Rails 7.1.0
    

    98.

    Let's create

    $ rails --version
    Rails 7.1.0
    

    98, with the following contents:

    Rails.application.routes.draw do
      get "/articles", to: "articles
    # index"
      # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
    end
    

    2

    Now we can see the article when we visit http://localhost:3000/articles/1!

    To finish up, let's add a convenient way to get to an article's page. We'll link each article's title in

    $ rails --version
    Rails 7.1.0
    

    13 to its page:

    Rails.application.routes.draw do
      get "/articles", to: "articles
    # index"
      # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
    end
    

    3

    So far, we've covered the "R" (Read) of CRUD. We will eventually cover the "C" (Create), "U" (Update), and "D" (Delete). As you might have guessed, we will do so by adding new routes, controller actions, and views. Whenever we have such a combination of routes, controller actions, and views that work together to perform CRUD operations on an entity, we call that entity a resource. For example, in our application, we would say an article is a resource.

    Rails provides a routes method named 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

    $ rails --version
    Rails 7.1.0
    

    82 routes in

    $ rails --version
    Rails 7.1.0
    

    01 with

    Rails.application.routes.draw do
      get "/articles", to: "articles
    # index"
      # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
    end
    

    01:

    Rails.application.routes.draw do
      get "/articles", to: "articles
    # index"
      # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
    end
    

    4

    We can inspect what routes are mapped by running the

    Rails.application.routes.draw do
      get "/articles", to: "articles
    # index"
      # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
    end
    

    05 command:

    Rails.application.routes.draw do
      get "/articles", to: "articles
    # index"
      # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
    end
    

    5

    The

    Rails.application.routes.draw do
      get "/articles", to: "articles
    # index"
      # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
    end
    

    01 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

    Rails.application.routes.draw do
      get "/articles", to: "articles
    # index"
      # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
    end
    

    07 or

    Rails.application.routes.draw do
      get "/articles", to: "articles
    # index"
      # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
    end
    

    08 form the names of these helpers. For example, the

    Rails.application.routes.draw do
      get "/articles", to: "articles
    # index"
      # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
    end
    

    09 helper returns

    Rails.application.routes.draw do
      get "/articles", to: "articles
    # index"
      # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
    end
    

    10 when given an article. We can use it to tidy up our links in

    $ rails --version
    Rails 7.1.0
    

    13:

    Rails.application.routes.draw do
      get "/articles", to: "articles
    # index"
      # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
    end
    

    6

    However, we will take this one step further by using the helper. The

    Rails.application.routes.draw do
      get "/articles", to: "articles
    # index"
      # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
    end
    

    12 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,

    Rails.application.routes.draw do
      get "/articles", to: "articles
    # index"
      # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
    end
    

    12 will call the appropriate path helper to convert the object to a path. For example, if we pass an article,

    Rails.application.routes.draw do
      get "/articles", to: "articles
    # index"
      # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
    end
    

    12 will call

    Rails.application.routes.draw do
      get "/articles", to: "articles
    # index"
      # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
    end
    

    09. So

    $ rails --version
    Rails 7.1.0
    

    13 becomes:

    Rails.application.routes.draw do
      get "/articles", to: "articles
    # index"
      # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
    end
    

    7

    Nice!

    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.

    In a Rails application, these steps are conventionally handled by a controller's

    Rails.application.routes.draw do
      get "/articles", to: "articles
    # index"
      # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
    end
    

    18 and

    Rails.application.routes.draw do
      get "/articles", to: "articles
    # index"
      # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
    end
    

    19 actions. Let's add a typical implementation of these actions to

    $ rails --version
    Rails 7.1.0
    

    09, below the

    $ rails --version
    Rails 7.1.0
    

    89 action:

    Rails.application.routes.draw do
      get "/articles", to: "articles
    # index"
      # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
    end
    

    8

    The

    Rails.application.routes.draw do
      get "/articles", to: "articles
    # index"
      # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
    end
    

    18 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

    Rails.application.routes.draw do
      get "/articles", to: "articles
    # index"
      # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
    end
    

    18 action will render

    Rails.application.routes.draw do
      get "/articles", to: "articles
    # index"
      # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
    end
    

    24, which we will create next.

    The

    Rails.application.routes.draw do
      get "/articles", to: "articles
    # index"
      # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
    end
    

    19 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

    Rails.application.routes.draw do
      get "/articles", to: "articles
    # index"
      # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
    end
    

    26. Else, the action redisplays the form by rendering

    Rails.application.routes.draw do
      get "/articles", to: "articles
    # index"
      # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
    end
    

    24 with status code 422 Unprocessable Entity. The title and body here are dummy values. After we create the form, we will come back and change these.

    will cause the browser to make a new request, whereas renders the specified view for the current request. It is important to use

    Rails.application.routes.draw do
      get "/articles", to: "articles
    # index"
      # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
    end
    

    28 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.

    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

    Rails.application.routes.draw do
      get "/articles", to: "articles
    # index"
      # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
    end
    

    24 with the following contents:

    Rails.application.routes.draw do
      get "/articles", to: "articles
    # index"
      # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
    end
    

    9

    The helper method instantiates a form builder. In the

    Rails.application.routes.draw do
      get "/articles", to: "articles
    # index"
      # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
    end
    

    32 block we call methods like and on the form builder to output the appropriate form elements.

    The resulting output from our

    Rails.application.routes.draw do
      get "/articles", to: "articles
    # index"
      # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
    end
    

    32 call will look like:

    $ bin/rails generate controller Articles index --skip-routes
    

    0

    Submitted form data is put into the

    $ rails --version
    Rails 7.1.0
    

    84 Hash, alongside captured route parameters. Thus, the

    Rails.application.routes.draw do
      get "/articles", to: "articles
    # index"
      # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
    end
    

    19 action can access the submitted title via

    Rails.application.routes.draw do
      get "/articles", to: "articles
    # index"
      # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
    end
    

    39 and the submitted body via

    Rails.application.routes.draw do
      get "/articles", to: "articles
    # index"
      # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
    end
    

    40. We could pass these values individually to

    Rails.application.routes.draw do
      get "/articles", to: "articles
    # index"
      # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
    end
    

    41, 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

    Rails.application.routes.draw do
      get "/articles", to: "articles
    # index"
      # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
    end
    

    42 Hash directly to

    Rails.application.routes.draw do
      get "/articles", to: "articles
    # index"
      # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
    end
    

    41, Rails will raise a

    Rails.application.routes.draw do
      get "/articles", to: "articles
    # index"
      # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
    end
    

    44 to alert us about the problem. So we will use a feature of Rails called Strong Parameters to filter

    $ rails --version
    Rails 7.1.0
    

    84. Think of it as strong typing for

    $ rails --version
    Rails 7.1.0
    

    84.

    Let's add a private method to the bottom of

    $ rails --version
    Rails 7.1.0
    

    09 named

    Rails.application.routes.draw do
      get "/articles", to: "articles
    # index"
      # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
    end
    

    48 that filters

    $ rails --version
    Rails 7.1.0
    

    84. And let's change

    Rails.application.routes.draw do
      get "/articles", to: "articles
    # index"
      # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
    end
    

    19 to use it:

    $ bin/rails generate controller Articles index --skip-routes
    

    1

    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

    Rails.application.routes.draw do
      get "/articles", to: "articles
    # index"
      # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
    end
    

    51 attribute of the model object.

    Let's add some validations to our model in

    $ rails --version
    Rails 7.1.0
    

    35:

    $ bin/rails generate controller Articles index --skip-routes
    

    2

    The first validation declares that a

    $ rails --version
    Rails 7.1.0
    

    43 value must be present. Because

    $ rails --version
    Rails 7.1.0
    

    43 is a string, this means that the

    $ rails --version
    Rails 7.1.0
    

    43 value must contain at least one non-whitespace character.

    The second validation declares that a

    $ rails --version
    Rails 7.1.0
    

    44 value must also be present. Additionally, it declares that the

    $ rails --version
    Rails 7.1.0
    

    44 value must be at least 10 characters long.

    You may be wondering where the

    $ rails --version
    Rails 7.1.0
    

    43 and

    $ rails --version
    Rails 7.1.0
    

    44 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

    Rails.application.routes.draw do
      get "/articles", to: "articles
    # index"
      # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
    end
    

    24 to display any error messages for

    $ rails --version
    Rails 7.1.0
    

    43 and

    $ rails --version
    Rails 7.1.0
    

    44:

    $ bin/rails generate controller Articles index --skip-routes
    

    3

    The 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

    Rails.application.routes.draw do
      get "/articles", to: "articles
    # index"
      # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
    end
    

    18 and

    Rails.application.routes.draw do
      get "/articles", to: "articles
    # index"
      # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
    end
    

    19 controller actions:

    $ bin/rails generate controller Articles index --skip-routes
    

    4

    When we visit http://localhost:3000/articles/new, the

    Rails.application.routes.draw do
      get "/articles", to: "articles
    # index"
      # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
    end
    

    66 request is mapped to the

    Rails.application.routes.draw do
      get "/articles", to: "articles
    # index"
      # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
    end
    

    18 action. The

    Rails.application.routes.draw do
      get "/articles", to: "articles
    # index"
      # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
    end
    

    18 action does not attempt to save

    $ rails --version
    Rails 7.1.0
    

    96. Therefore, validations are not checked, and there will be no error messages.

    When we submit the form, the

    Rails.application.routes.draw do
      get "/articles", to: "articles
    # index"
      # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
    end
    

    70 request is mapped to the

    Rails.application.routes.draw do
      get "/articles", to: "articles
    # index"
      # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
    end
    

    19 action. The

    Rails.application.routes.draw do
      get "/articles", to: "articles
    # index"
      # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
    end
    

    19 action does attempt to save

    $ rails --version
    Rails 7.1.0
    

    96. Therefore, validations are checked. If any validation fails,

    $ rails --version
    Rails 7.1.0
    

    96 will not be saved, and

    Rails.application.routes.draw do
      get "/articles", to: "articles
    # index"
      # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
    end
    

    24 will be rendered with error messages.

    We can now create an article by visiting http://localhost:3000/articles/new. To finish up, let's link to that page from the bottom of

    $ rails --version
    Rails 7.1.0
    

    13:

    $ bin/rails generate controller Articles index --skip-routes
    

    5

    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

    Rails.application.routes.draw do
      get "/articles", to: "articles
    # index"
      # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
    end
    

    77 and

    Rails.application.routes.draw do
      get "/articles", to: "articles
    # index"
      # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
    end
    

    78 actions. Let's add a typical implementation of these actions to

    $ rails --version
    Rails 7.1.0
    

    09, below the

    Rails.application.routes.draw do
      get "/articles", to: "articles
    # index"
      # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
    end
    

    19 action:

    $ bin/rails generate controller Articles index --skip-routes
    

    6

    Notice how the

    Rails.application.routes.draw do
      get "/articles", to: "articles
    # index"
      # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
    end
    

    77 and

    Rails.application.routes.draw do
      get "/articles", to: "articles
    # index"
      # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
    end
    

    78 actions resemble the

    Rails.application.routes.draw do
      get "/articles", to: "articles
    # index"
      # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
    end
    

    18 and

    Rails.application.routes.draw do
      get "/articles", to: "articles
    # index"
      # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
    end
    

    19 actions.

    The

    Rails.application.routes.draw do
      get "/articles", to: "articles
    # index"
      # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
    end
    

    77 action fetches the article from the database, and stores it in

    $ rails --version
    Rails 7.1.0
    

    96 so that it can be used when building the form. By default, the

    Rails.application.routes.draw do
      get "/articles", to: "articles
    # index"
      # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
    end
    

    77 action will render

    Rails.application.routes.draw do
      get "/articles", to: "articles
    # index"
      # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
    end
    

    88.

    The

    Rails.application.routes.draw do
      get "/articles", to: "articles
    # index"
      # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
    end
    

    78 action (re-)fetches the article from the database, and attempts to update it with the submitted form data filtered by

    Rails.application.routes.draw do
      get "/articles", to: "articles
    # index"
      # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
    end
    

    48. 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

    Rails.application.routes.draw do
      get "/articles", to: "articles
    # index"
      # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
    end
    

    88.

    Our

    Rails.application.routes.draw do
      get "/articles", to: "articles
    # index"
      # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
    end
    

    77 form will look the same as our

    Rails.application.routes.draw do
      get "/articles", to: "articles
    # index"
      # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
    end
    

    18 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

    Rails.application.routes.draw do
      get "/articles", to: "articles
    # index"
      # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
    end
    

    94 with the following contents:

    $ bin/rails generate controller Articles index --skip-routes
    

    7

    The above code is the same as our form in

    Rails.application.routes.draw do
      get "/articles", to: "articles
    # index"
      # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
    end
    

    24, except that all occurrences of

    $ rails --version
    Rails 7.1.0
    

    96 have been replaced with

    $ rails --version
    Rails 7.1.0
    

    54. 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

    Rails.application.routes.draw do
      get "/articles", to: "articles
    # index"
      # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
    end
    

    24 to use the partial via :

    $ bin/rails generate controller Articles index --skip-routes
    

    8

    A partial's filename must be prefixed with an underscore, e.g.

    $ bin/rails generate controller Articles index --skip-routes
    

    00. But when rendering, it is referenced without the underscore, e.g.

    $ bin/rails generate controller Articles index --skip-routes
    

    01.

    And now, let's create a very similar

    Rails.application.routes.draw do
      get "/articles", to: "articles
    # index"
      # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
    end
    

    88:

    $ bin/rails generate controller Articles index --skip-routes
    

    9

    We can now update an article by visiting its edit page, e.g. http://localhost:3000/articles/1/edit. To finish up, let's link to the edit page from the bottom of

    $ rails --version
    Rails 7.1.0
    

    98:

    create  app/controllers/articles_controller.rb
    invoke  erb
    create    app/views/articles
    create    app/views/articles/index.html.erb
    invoke  test_unit
    create    test/controllers/articles_controller_test.rb
    invoke  helper
    create    app/helpers/articles_helper.rb
    invoke    test_unit
    

    0

    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 (

    $ bin/rails generate controller Articles index --skip-routes
    

    1. already provides the route, which maps

    $ bin/rails generate controller Articles index --skip-routes
    

    05 requests to the

    $ bin/rails generate controller Articles index --skip-routes
    

    06 action of

    $ rails --version
    Rails 7.1.0
    

    05.

    So, let's add a typical

    $ bin/rails generate controller Articles index --skip-routes
    

    06 action to

    $ rails --version
    Rails 7.1.0
    

    09, below the

    Rails.application.routes.draw do
      get "/articles", to: "articles
    # index"
      # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
    end
    

    78 action:

    create  app/controllers/articles_controller.rb
    invoke  erb
    create    app/views/articles
    create    app/views/articles/index.html.erb
    invoke  test_unit
    create    test/controllers/articles_controller_test.rb
    invoke  helper
    create    app/helpers/articles_helper.rb
    invoke    test_unit
    

    1

    The

    $ bin/rails generate controller Articles index --skip-routes
    

    06 action fetches the article from the database, and calls on it. Then, it redirects the browser to the root path with status code 303 See Other.

    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.

    $ bin/rails generate controller Articles index --skip-routes
    

    13.

    Now let's add a link at the bottom of

    $ rails --version
    Rails 7.1.0
    

    98 so that we can delete an article from its own page:

    create  app/controllers/articles_controller.rb
    invoke  erb
    create    app/views/articles
    create    app/views/articles/index.html.erb
    invoke  test_unit
    create    test/controllers/articles_controller_test.rb
    invoke  helper
    create    app/helpers/articles_helper.rb
    invoke    test_unit
    

    2

    In the above code, we use the

    $ bin/rails generate controller Articles index --skip-routes
    

    15 option to set the

    $ bin/rails generate controller Articles index --skip-routes
    

    16 and

    $ bin/rails generate controller Articles index --skip-routes
    

    17 HTML attributes of the "Destroy" link. Both of these attributes hook into Turbo, which is included by default in fresh Rails applications.

    $ bin/rails generate controller Articles index --skip-routes
    

    18 will cause the link to make a

    $ bin/rails generate controller Articles index --skip-routes
    

    19 request instead of a

    $ bin/rails generate controller Articles index --skip-routes
    

    20 request.

    $ bin/rails generate controller Articles index --skip-routes
    

    21 will cause a confirmation dialog to appear when the link is clicked. If the user cancels the dialog, the request will be aborted.

    And that's it! We can now list, show, create, update, and delete articles! InCRUDable!

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

    We're going to see the same generator that we used before when creating the

    $ rails --version
    Rails 7.1.0
    

    51 model. This time we'll create a

    $ bin/rails generate controller Articles index --skip-routes
    

    23 model to hold a reference to an article. Run this command in your terminal:

    create  app/controllers/articles_controller.rb
    invoke  erb
    create    app/views/articles
    create    app/views/articles/index.html.erb
    invoke  test_unit
    create    test/controllers/articles_controller_test.rb
    invoke  helper
    create    app/helpers/articles_helper.rb
    invoke    test_unit
    

    3

    This command will generate four files:

    File Purpose db/migrate/20140120201010_create_comments.rb Migration to create the comments table in your database (your name will include a different timestamp) app/models/comment.rb The Comment model test/models/comment_test.rb Testing harness for the comment model test/fixtures/comments.yml Sample comments for use in testing

    First, take a look at

    $ bin/rails generate controller Articles index --skip-routes
    

    24:

    create  app/controllers/articles_controller.rb
    invoke  erb
    create    app/views/articles
    create    app/views/articles/index.html.erb
    invoke  test_unit
    create    test/controllers/articles_controller_test.rb
    invoke  helper
    create    app/helpers/articles_helper.rb
    invoke    test_unit
    

    4

    This is very similar to the

    $ rails --version
    Rails 7.1.0
    

    51 model that you saw earlier. The difference is the line

    $ bin/rails generate controller Articles index --skip-routes
    

    26, which sets up an Active Record association. You'll learn a little about associations in the next section of this guide.

    The (

    $ bin/rails generate controller Articles index --skip-routes
    

    1. keyword used in the shell command is a special data type for models. It creates a new column on your database table with the provided model name appended with an

    $ bin/rails generate controller Articles index --skip-routes
    

    28 that can hold integer values. To get a better understanding, analyze the

    $ bin/rails generate controller Articles index --skip-routes
    

    29 file after running the migration.

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

    create  app/controllers/articles_controller.rb
    invoke  erb
    create    app/views/articles
    create    app/views/articles/index.html.erb
    invoke  test_unit
    create    test/controllers/articles_controller_test.rb
    invoke  helper
    create    app/helpers/articles_helper.rb
    invoke    test_unit
    

    5

    The

    $ bin/rails generate controller Articles index --skip-routes
    

    30 line creates an integer column called

    $ bin/rails generate controller Articles index --skip-routes
    

    31, an index for it, and a foreign key constraint that points to the

    $ rails --version
    Rails 7.1.0
    

    39 column of the

    $ rails --version
    Rails 7.1.0
    

    37 table. Go ahead and run the migration:

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

    create  app/controllers/articles_controller.rb
    invoke  erb
    create    app/views/articles
    create    app/views/articles/index.html.erb
    invoke  test_unit
    create    test/controllers/articles_controller_test.rb
    invoke  helper
    create    app/helpers/articles_helper.rb
    invoke    test_unit
    

    6

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

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

    In fact, this is very close to the syntax that Rails uses to declare this association. You've already seen the line of code inside the

    $ bin/rails generate controller Articles index --skip-routes
    

    23 model (app/models/comment.rb) that makes each comment belong to an Article:

    create  app/controllers/articles_controller.rb
    invoke  erb
    create    app/views/articles
    create    app/views/articles/index.html.erb
    invoke  test_unit
    create    test/controllers/articles_controller_test.rb
    invoke  helper
    create    app/helpers/articles_helper.rb
    invoke    test_unit
    

    4

    You'll need to edit

    $ rails --version
    Rails 7.1.0
    

    35 to add the other side of the association:

    create  app/controllers/articles_controller.rb
    invoke  erb
    create    app/views/articles
    create    app/views/articles/index.html.erb
    invoke  test_unit
    create    test/controllers/articles_controller_test.rb
    invoke  helper
    create    app/helpers/articles_helper.rb
    invoke    test_unit
    

    8

    These two declarations enable a good bit of automatic behavior. For example, if you have an instance variable

    $ rails --version
    Rails 7.1.0
    

    96 containing an article, you can retrieve all the comments belonging to that article as an array using

    $ bin/rails generate controller Articles index --skip-routes
    

    37.

    As with the

    $ rails --version
    Rails 7.1.0
    

    37 controller, we will need to add a route so that Rails knows where we would like to navigate to see

    $ bin/rails generate controller Articles index --skip-routes
    

    39. Open up the

    $ rails --version
    Rails 7.1.0
    

    01 file again, and edit it as follows:

    create  app/controllers/articles_controller.rb
    invoke  erb
    create    app/views/articles
    create    app/views/articles/index.html.erb
    invoke  test_unit
    create    test/controllers/articles_controller_test.rb
    invoke  helper
    create    app/helpers/articles_helper.rb
    invoke    test_unit
    

    9

    This creates

    $ bin/rails generate controller Articles index --skip-routes
    

    39 as a nested resource within

    $ rails --version
    Rails 7.1.0
    

    37. This is another part of capturing the hierarchical relationship that exists between articles and comments.

    For more information on routing, see the Rails Routing guide.

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

    class ArticlesController < ApplicationController
      def index
      end
    end
    

    0

    This creates three files and one empty directory:

    File/Directory Purpose app/controllers/comments_controller.rb The Comments controller app/views/comments/ Views of the controller are stored here test/controllers/comments_controller_test.rb The test for the controller app/helpers/comments_helper.rb A view helper file

    Like with any blog, our readers will create their comments directly after reading the article, and once they have added their comment, will be sent back to the article show page to see their comment now listed. Due to this, our

    $ bin/rails generate controller Articles index --skip-routes
    

    43 is there to provide a method to create comments and delete spam comments when they arrive.

    So first, we'll wire up the Article show template (

    $ rails --version
    Rails 7.1.0
    

    1. to let us make a new comment:

    class ArticlesController < ApplicationController
      def index
      end
    end
    

    1

    This adds a form on the

    $ rails --version
    Rails 7.1.0
    

    51 show page that creates a new comment by calling the

    $ bin/rails generate controller Articles index --skip-routes
    

    43

    Rails.application.routes.draw do
      get "/articles", to: "articles
    # index"
      # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
    end
    

    19 action. The

    Rails.application.routes.draw do
      get "/articles", to: "articles
    # index"
      # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
    end
    

    32 call here uses an array, which will build a nested route, such as

    $ bin/rails generate controller Articles index --skip-routes
    

    49.

    Let's wire up the

    Rails.application.routes.draw do
      get "/articles", to: "articles
    # index"
      # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
    end
    

    19 in

    $ bin/rails generate controller Articles index --skip-routes
    

    51:

    class ArticlesController < ApplicationController
      def index
      end
    end
    

    2

    You'll see a bit more complexity here than you did in the controller for articles. That's a side-effect of the nesting that you've set up. Each request for a comment has to keep track of the article to which the comment is attached, thus the initial call to the

    $ rails --version
    Rails 7.1.0
    

    58 method of the

    $ rails --version
    Rails 7.1.0
    

    51 model to get the article in question.

    In addition, the code takes advantage of some of the methods available for an association. We use the

    Rails.application.routes.draw do
      get "/articles", to: "articles
    # index"
      # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
    end
    

    19 method on

    $ bin/rails generate controller Articles index --skip-routes
    

    37 to create and save the comment. This will automatically link the comment so that it belongs to that particular article.

    Once we have made the new comment, we send the user back to the original article using the

    $ bin/rails generate controller Articles index --skip-routes
    

    56 helper. As we have already seen, this calls the

    $ rails --version
    Rails 7.1.0
    

    89 action of the

    $ rails --version
    Rails 7.1.0
    

    05 which in turn renders the

    $ bin/rails generate controller Articles index --skip-routes
    

    59 template. This is where we want the comment to show, so let's add that to the

    $ rails --version
    Rails 7.1.0
    

    98.

    class ArticlesController < ApplicationController
      def index
      end
    end
    

    3

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

    Series hướng dẫn lập trình ruby on rails phần 2

    Now that we have articles and comments working, take a look at the

    $ rails --version
    Rails 7.1.0
    

    98 template. It is getting long and awkward. We can use partials to clean it up.

    First, we will make a comment partial to extract showing all the comments for the article. Create the file

    $ bin/rails generate controller Articles index --skip-routes
    

    62 and put the following into it:

    class ArticlesController < ApplicationController
      def index
      end
    end
    

    4

    Then you can change

    $ rails --version
    Rails 7.1.0
    

    98 to look like the following:

    class ArticlesController < ApplicationController
      def index
      end
    end
    

    5

    This will now render the partial in

    $ bin/rails generate controller Articles index --skip-routes
    

    62 once for each comment that is in the

    $ bin/rails generate controller Articles index --skip-routes
    

    37 collection. As the

    Rails.application.routes.draw do
      get "/articles", to: "articles
    # index"
      # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
    end
    

    29 method iterates over the

    $ bin/rails generate controller Articles index --skip-routes
    

    37 collection, it assigns each comment to a local variable named the same as the partial, in this case

    $ bin/rails generate controller Articles index --skip-routes
    

    68, which is then available in the partial for us to show.

    Let us also move that new comment section out to its own partial. Again, you create a file

    $ bin/rails generate controller Articles index --skip-routes
    

    69 containing:

    class ArticlesController < ApplicationController
      def index
      end
    end
    

    6

    Then you make the

    $ rails --version
    Rails 7.1.0
    

    98 look like the following:

    class ArticlesController < ApplicationController
      def index
      end
    end
    

    7

    The second render just defines the partial template we want to render,

    $ bin/rails generate controller Articles index --skip-routes
    

    71. Rails is smart enough to spot the forward slash in that string and realize that you want to render the

    $ bin/rails generate controller Articles index --skip-routes
    

    00 file in the

    $ bin/rails generate controller Articles index --skip-routes
    

    73 directory.

    The

    $ rails --version
    Rails 7.1.0
    

    96 object is available to any partials rendered in the view because we defined it as an instance variable.

    Concerns are a way to make large controllers or models easier to understand and manage. This also has the advantage of reusability when multiple models (or controllers) share the same concerns. Concerns are implemented using modules that contain methods representing a well-defined slice of the functionality that a model or controller is responsible for. In other languages, modules are often known as mixins.

    You can use concerns in your controller or model the same way you would use any module. When you first created your app with

    $ bin/rails generate controller Articles index --skip-routes
    

    75, two folders were created within

    $ bin/rails generate controller Articles index --skip-routes
    

    76 along with the rest:

    class ArticlesController < ApplicationController
      def index
      end
    end
    

    8

    In the example below, we will implement a new feature for our blog that would benefit from using a concern. Then, we will create a concern, and refactor the code to use it, making the code more DRY and maintainable.

    A blog article might have various statuses - for instance, it might be visible to everyone (i.e.

    $ bin/rails generate controller Articles index --skip-routes
    

    77), or only visible to the author (i.e.

    $ bin/rails generate controller Articles index --skip-routes
    

    78). It may also be hidden to all but still retrievable (i.e.

    $ bin/rails generate controller Articles index --skip-routes
    

    79). Comments may similarly be hidden or visible. This could be represented using a

    $ bin/rails generate controller Articles index --skip-routes
    

    80 column in each model.

    First, let's run the following migrations to add

    $ bin/rails generate controller Articles index --skip-routes
    

    80 to

    $ bin/rails generate controller Articles index --skip-routes
    

    82 and

    $ bin/rails generate controller Articles index --skip-routes
    

    83:

    class ArticlesController < ApplicationController
      def index
      end
    end
    

    9

    And next, let's update the database with the generated migrations:

    To choose the status for the existing articles and comments you can add a default value to the generated migration files by adding the

    $ bin/rails generate controller Articles index --skip-routes
    

    84 option and launch the migrations again. You can also call in a rails console

    $ bin/rails generate controller Articles index --skip-routes
    

    85 and

    $ bin/rails generate controller Articles index --skip-routes
    

    86.

    We also have to permit the

    $ bin/rails generate controller Articles index --skip-routes
    

    87 key as part of the strong parameter, in

    $ rails --version
    Rails 7.1.0
    

    09:

    Rails.application.routes.draw do
      root "articles
    # index"
      get "/articles", to: "articles
    # index"
    end
    

    0

    and in

    $ bin/rails generate controller Articles index --skip-routes
    

    51:

    Rails.application.routes.draw do
      root "articles
    # index"
      get "/articles", to: "articles
    # index"
    end
    

    1

    Within the

    $ rails --version
    Rails 7.1.0
    

    54 model, after running a migration to add a

    $ bin/rails generate controller Articles index --skip-routes
    

    80 column using

    $ bin/rails generate controller Articles index --skip-routes
    

    92 command, you would add:

    Rails.application.routes.draw do
      root "articles
    # index"
      get "/articles", to: "articles
    # index"
    end
    

    2

    and in the

    $ bin/rails generate controller Articles index --skip-routes
    

    23 model:

    Rails.application.routes.draw do
      root "articles
    # index"
      get "/articles", to: "articles
    # index"
    end
    

    3

    Then, in our

    $ rails --version
    Rails 7.1.0
    

    04 action template (

    $ rails --version
    Rails 7.1.0
    

    1. we would use the

    $ bin/rails generate controller Articles index --skip-routes
    

    96 method to avoid displaying any article that is archived:

    Rails.application.routes.draw do
      root "articles
    # index"
      get "/articles", to: "articles
    # index"
    end
    

    4

    Similarly, in our comment partial view (

    $ bin/rails generate controller Articles index --skip-routes
    

    1. we would use the

    $ bin/rails generate controller Articles index --skip-routes
    

    96 method to avoid displaying any comment that is archived:

    Rails.application.routes.draw do
      root "articles
    # index"
      get "/articles", to: "articles
    # index"
    end
    

    5

    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.

    A concern is only responsible for a focused subset of the model's responsibility; the methods in our concern will all be related to the visibility of a model. Let's call our new concern (module)

    $ bin/rails generate controller Articles index --skip-routes
    

    99. We can create a new file inside

    create  app/controllers/articles_controller.rb
    invoke  erb
    create    app/views/articles
    create    app/views/articles/index.html.erb
    invoke  test_unit
    create    test/controllers/articles_controller_test.rb
    invoke  helper
    create    app/helpers/articles_helper.rb
    invoke    test_unit
    

    00 called

    create  app/controllers/articles_controller.rb
    invoke  erb
    create    app/views/articles
    create    app/views/articles/index.html.erb
    invoke  test_unit
    create    test/controllers/articles_controller_test.rb
    invoke  helper
    create    app/helpers/articles_helper.rb
    invoke    test_unit
    

    01 , and store all of the status methods that were duplicated in the models.

    create  app/controllers/articles_controller.rb
    invoke  erb
    create    app/views/articles
    create    app/views/articles/index.html.erb
    invoke  test_unit
    create    test/controllers/articles_controller_test.rb
    invoke  helper
    create    app/helpers/articles_helper.rb
    invoke    test_unit
    

    02

    Rails.application.routes.draw do
      root "articles
    # index"
      get "/articles", to: "articles
    # index"
    end
    

    6

    We can add our status validation to the concern, but this is slightly more complex as validations are methods called at the class level. The

    create  app/controllers/articles_controller.rb
    invoke  erb
    create    app/views/articles
    create    app/views/articles/index.html.erb
    invoke  test_unit
    create    test/controllers/articles_controller_test.rb
    invoke  helper
    create    app/helpers/articles_helper.rb
    invoke    test_unit
    

    03 (API Guide) gives us a simpler way to include them:

    Rails.application.routes.draw do
      root "articles
    # index"
      get "/articles", to: "articles
    # index"
    end
    

    7

    Now, we can remove the duplicated logic from each model and instead include our new

    $ bin/rails generate controller Articles index --skip-routes
    

    99 module:

    In

    $ rails --version
    Rails 7.1.0
    

    35:

    Rails.application.routes.draw do
      root "articles
    # index"
      get "/articles", to: "articles
    # index"
    end
    

    8

    and in

    $ bin/rails generate controller Articles index --skip-routes
    

    24:

    Rails.application.routes.draw do
      root "articles
    # index"
      get "/articles", to: "articles
    # index"
    end
    

    9

    Class methods can also be added to concerns. If we want to display a count of public articles or comments on our main page, we might add a class method to Visible as follows:

    require "application_controller" # DON'T DO THIS.
    

    0

    Then in the view, you can call it like any class method:

    require "application_controller" # DON'T DO THIS.
    

    1

    To finish up, we will add a select box to the forms, and let the user select the status when they create a new article or post a new comment. We can also select the status of the object, or a default of

    $ bin/rails generate controller Articles index --skip-routes
    

    77 if it hasn't been set yet. In

    Rails.application.routes.draw do
      get "/articles", to: "articles
    # index"
      # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
    end
    

    94, we can add:

    require "application_controller" # DON'T DO THIS.
    

    2

    and in

    $ bin/rails generate controller Articles index --skip-routes
    

    69:

    require "application_controller" # DON'T DO THIS.
    

    3

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

    $ bin/rails generate controller Articles index --skip-routes
    

    06 action in the

    $ bin/rails generate controller Articles index --skip-routes
    

    43.

    So first, let's add the delete link in the

    $ bin/rails generate controller Articles index --skip-routes
    

    62 partial:

    require "application_controller" # DON'T DO THIS.
    

    4

    Clicking this new "Destroy Comment" link will fire off a

    create  app/controllers/articles_controller.rb
    invoke  erb
    create    app/views/articles
    create    app/views/articles/index.html.erb
    invoke  test_unit
    create    test/controllers/articles_controller_test.rb
    invoke  helper
    create    app/helpers/articles_helper.rb
    invoke    test_unit
    

    13 to our

    $ bin/rails generate controller Articles index --skip-routes
    

    43, which can then use this to find the comment we want to delete, so let's add a

    $ bin/rails generate controller Articles index --skip-routes
    

    06 action to our controller (

    $ bin/rails generate controller Articles index --skip-routes
    

    51):

    require "application_controller" # DON'T DO THIS.
    

    5

    The

    $ bin/rails generate controller Articles index --skip-routes
    

    06 action will find the article we are looking at, locate the comment within the

    $ bin/rails generate controller Articles index --skip-routes
    

    37 collection, and then remove it from the database and send us back to the show action for the article.

    If you delete an article, its associated comments will also need to be deleted, otherwise they would simply occupy space in the database. Rails allows you to use the

    create  app/controllers/articles_controller.rb
    invoke  erb
    create    app/views/articles
    create    app/views/articles/index.html.erb
    invoke  test_unit
    create    test/controllers/articles_controller_test.rb
    invoke  helper
    create    app/helpers/articles_helper.rb
    invoke    test_unit
    

    19 option of an association to achieve this. Modify the Article model,

    $ rails --version
    Rails 7.1.0
    

    35, as follows:

    require "application_controller" # DON'T DO THIS.
    

    6

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

    Rails provides an HTTP authentication system that will work nicely in this situation.

    In the

    $ rails --version
    Rails 7.1.0
    

    05 we need to have a way to block access to the various actions if the person is not authenticated. Here we can use the Rails

    create  app/controllers/articles_controller.rb
    invoke  erb
    create    app/views/articles
    create    app/views/articles/index.html.erb
    invoke  test_unit
    create    test/controllers/articles_controller_test.rb
    invoke  helper
    create    app/helpers/articles_helper.rb
    invoke    test_unit
    

    22 method, which allows access to the requested action if that method allows it.

    To use the authentication system, we specify it at the top of our

    $ rails --version
    Rails 7.1.0
    

    05 in

    $ rails --version
    Rails 7.1.0
    

    09. In our case, we want the user to be authenticated on every action except

    $ rails --version
    Rails 7.1.0
    

    04 and

    $ rails --version
    Rails 7.1.0
    

    89, so we write that:

    require "application_controller" # DON'T DO THIS.
    

    7

    We also want to allow only authenticated users to delete comments, so in the

    $ bin/rails generate controller Articles index --skip-routes
    

    43 (

    $ bin/rails generate controller Articles index --skip-routes
    

    1. we write:

    require "application_controller" # DON'T DO THIS.
    

    8

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

    Series hướng dẫn lập trình ruby on rails phần 2

    After entering the correct username and password, you will remain authenticated until a different username and password is required or the browser is closed.

    Other authentication methods are available for Rails applications. Two popular authentication add-ons for Rails are the Devise rails engine and the Authlogic gem, along with a number of others.

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

    Now that you've seen your first Rails application, you should feel free to update it and experiment on your own.

    Remember, you don't have to do everything without help. As you need assistance getting up and running with Rails, feel free to consult these support resources:

    • The Ruby on Rails Guides
    • The Ruby on Rails mailing list

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

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

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

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

    Feedback

    You're encouraged to help improve the quality of this guide.

    Please contribute if you see any typos or factual errors. To get started, you can read our section.

    You may also find incomplete content or stuff that is not up to date. Please do add any missing documentation for main. Make sure to check Edge Guides first to verify if the issues are already fixed or not on the main branch. Check the Ruby on Rails Guides Guidelines for style and conventions.

    If for whatever reason you spot something to fix but cannot patch it yourself, please open an issue.

    And last but not least, any kind of discussion regarding Ruby on Rails documentation is very welcome on the official Ruby on Rails Forum.