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:
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:
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
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
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
1. Before you install Rails, you should check to make sure that your system has the proper prerequisites installed. These include:
Open up a command line prompt. On macOS open Terminal.app; on Windows choose "Run" from your Start menu and type
2. Any commands prefaced with a dollar sign
0 should be run in the command line. Verify that you have a current version of Ruby installed:
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
4: The program should report its version. To install Rails, use the
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:
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
9 directory and install the gem dependencies that are already mentioned in
7 using
8. You can see all of the command line options that the Rails application generator accepts by running
9. After you create the blog application, switch to its folder: The
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
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
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
3, you should add your own tasks by adding files to the
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
9 directory: If you are using Windows, you have to pass the scripts under the
6 folder directly to the Ruby interpreter e.g.
7. JavaScript asset compression requires you have a JavaScript runtime available on your system, in the absence of a runtime you will see an
8 error during asset compression. Usually macOS and Windows come with a JavaScript runtime installed.
9 is the recommended runtime for JRuby users and is added by default to the
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: 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,
01, at the top of the
02 block:
The route above declares that
03 requests are mapped to the
04 action of
05. To create
05 and its
04 action, we'll run the controller generator (with the
08 option because we already have an appropriate route):
Rails will create several files for you:
The most important of these is the controller file,
09. Let's take a look at it:
The
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
11 directory. So the
04 action will render
13 by default. Let's open
13, and replace its contents with: If you previously stopped the web server to run the controller generator, restart it with
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
01, and add the following
17 route to the top of the
02 block:
Now we can see our "Hello, Rails!" text when we visit http://localhost:3000, confirming that the
17 route is also mapped to the
04 action of
05. Rails applications do not use
22 to load application code. You may have noticed that
05 inherits from
24, but
09 does not have anything like
Application classes and modules are available everywhere, you do not need and should not load anything under
1 with
22. This feature is called autoloading, and you can learn more about it in Autoloading and Reloading Constants. You only need
22 calls for two use cases:
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:
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
32, not
33. This will create several files:
The two files we'll focus on are the migration file (
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:
0 The call to
36 specifies how the
37 table should be constructed. By default, the
36 method adds an
39 column as an auto-incrementing primary key. So the first record in the table will have an
39 of 1, the next record will have an
39 of 2, and so on. Inside the block for
36, two columns are defined:
43 and
44. These were added by the generator because we included them in our generate command (
45). On the last line of the block is a call to
46. This method defines two additional columns named
47 and
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:
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
49, but it also automatically loads Rails and our application code. Let's launch the console with this command: You should see an
49 prompt like:
2 At this prompt, we can initialize a new
51 object:
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 :
4 The above output shows an
53 database query. This indicates that the article has been inserted into our table. And if we take a look at the
54 object again, we see something interesting has happened:
5 The
39,
47, and
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
39 as an argument:
6 And when we want to fetch all articles from the database, we can call on the model:
7 This method returns an
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
09, and change the
04 action to fetch all articles from the database:
8 Controller instance variables can be accessed by the view. That means we can reference
64 in
13. Let's open that file, and replace its contents with:
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:
66 and
67. The
66 tag means "evaluate the enclosed Ruby code." The
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
70, we've enclosed that code in
66. But, since we do want to output the value returned by
72 (for each article), we've enclosed that code in
67. We can see the final result by visiting http://localhost:3000. (Remember that
15 must be running!) Here's what happens when we do that:
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
01, and insert the last route shown here:
0 The new route is another
82 route, but it has something extra in its path:
83. This designates a route parameter. A route parameter captures a segment of the request's path, and puts that value into the
84 Hash, which is accessible by the controller action. For example, when handling a request like
85,
86 would be captured as the value for
83, which would then be accessible as
88 in the
89 action of
05. Let's add that
89 action now, below the
04 action in
09:
1 The
89 action calls
95 () with the ID captured by the route parameter. The returned article is stored in the
96 instance variable, so it is accessible by the view. By default, the
89 action will render
98. Let's create
98, with the following contents:
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
13 to its page:
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
82 routes in
01 with
01:
4 We can inspect what routes are mapped by running the
05 command:
5 The
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
07 or
08 form the names of these helpers. For example, the
09 helper returns
10 when given an article. We can use it to tidy up our links in
13:
6 However, we will take this one step further by using the helper. The
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,
12 will call the appropriate path helper to convert the object to a path. For example, if we pass an article,
12 will call
09. So
13 becomes:
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
18 and
19 actions. Let's add a typical implementation of these actions to
09, below the
89 action:
8 The
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
18 action will render
24, which we will create next. The
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
26. Else, the action redisplays the form by rendering
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
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
24 with the following contents:
9 The helper method instantiates a form builder. In the
32 block we call methods like and on the form builder to output the appropriate form elements. The resulting output from our
32 call will look like:
0 Submitted form data is put into the
84 Hash, alongside captured route parameters. Thus, the
19 action can access the submitted title via
39 and the submitted body via
40. We could pass these values individually to
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
42 Hash directly to
41, Rails will raise a
44 to alert us about the problem. So we will use a feature of Rails called Strong Parameters to filter
84. Think of it as strong typing for
84. Let's add a private method to the bottom of
09 named
48 that filters
84. And let's change
19 to use it:
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
51 attribute of the model object. Let's add some validations to our model in
35:
2 The first validation declares that a
43 value must be present. Because
43 is a string, this means that the
43 value must contain at least one non-whitespace character. The second validation declares that a
44 value must also be present. Additionally, it declares that the
44 value must be at least 10 characters long. You may be wondering where the
43 and
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
24 to display any error messages for
43 and
44:
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
18 and
19 controller actions:
4 When we visit http://localhost:3000/articles/new, the
66 request is mapped to the
18 action. The
18 action does not attempt to save
96. Therefore, validations are not checked, and there will be no error messages. When we submit the form, the
70 request is mapped to the
19 action. The
19 action does attempt to save
96. Therefore, validations are checked. If any validation fails,
96 will not be saved, and
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
13:
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
77 and
78 actions. Let's add a typical implementation of these actions to
09, below the
19 action:
6 Notice how the
77 and
78 actions resemble the
18 and
19 actions. The
77 action fetches the article from the database, and stores it in
96 so that it can be used when building the form. By default, the
77 action will render
88. The
78 action (re-)fetches the article from the database, and attempts to update it with the submitted form data filtered by
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
88. Our
77 form will look the same as our
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
94 with the following contents:
7 The above code is the same as our form in
24, except that all occurrences of
96 have been replaced with
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
24 to use the partial via :
8 A partial's filename must be prefixed with an underscore, e.g.
00. But when rendering, it is referenced without the underscore, e.g.
01. And now, let's create a very similar
88:
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
98:
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 (
05 requests to the
06 action of
05. So, let's add a typical
06 action to
09, below the
78 action:
1 The
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.
13. Now let's add a link at the bottom of
98 so that we can delete an article from its own page:
2 In the above code, we use the
15 option to set the
16 and
17 HTML attributes of the "Destroy" link. Both of these attributes hook into Turbo, which is included by default in fresh Rails applications.
18 will cause the link to make a
19 request instead of a
20 request.
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
51 model. This time we'll create a
23 model to hold a reference to an article. Run this command in your terminal:
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
24:
4 This is very similar to the
51 model that you saw earlier. The difference is the line
26, which sets up an Active Record association. You'll learn a little about associations in the next section of this guide. The (
28 that can hold integer values. To get a better understanding, analyze the
29 file after running the migration. In addition to the model, Rails has also made a migration to create the corresponding database table:
5 The
30 line creates an integer column called
31, an index for it, and a foreign key constraint that points to the
39 column of the
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:
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:
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
23 model (app/models/comment.rb) that makes each comment belong to an Article:
4 You'll need to edit
35 to add the other side of the association:
8 These two declarations enable a good bit of automatic behavior. For example, if you have an instance variable
96 containing an article, you can retrieve all the comments belonging to that article as an array using
37. As with the
37 controller, we will need to add a route so that Rails knows where we would like to navigate to see
39. Open up the
01 file again, and edit it as follows:
9 This creates
39 as a nested resource within
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:
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
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 (
1 This adds a form on the
51 show page that creates a new comment by calling the
43
19 action. The
32 call here uses an array, which will build a nested route, such as
49. Let's wire up the
19 in
51:
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
58 method of the
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
19 method on
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
56 helper. As we have already seen, this calls the
89 action of the
05 which in turn renders the
59 template. This is where we want the comment to show, so let's add that to the
98.
3 Now you can add articles and comments to your blog and have them show up in the right places. Now that we have articles and comments working, take a look at the
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
62 and put the following into it:
4 Then you can change
98 to look like the following:
5 This will now render the partial in
62 once for each comment that is in the
37 collection. As the
29 method iterates over the
37 collection, it assigns each comment to a local variable named the same as the partial, in this case
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
69 containing:
6 Then you make the
98 look like the following:
7 The second render just defines the partial template we want to render,
71. Rails is smart enough to spot the forward slash in that string and realize that you want to render the
00 file in the
73 directory. The
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
75, two folders were created within
76 along with the rest:
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.
77), or only visible to the author (i.e.
78). It may also be hidden to all but still retrievable (i.e.
79). Comments may similarly be hidden or visible. This could be represented using a
80 column in each model. First, let's run the following migrations to add
80 to
82 and
83:
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
84 option and launch the migrations again. You can also call in a rails console
85 and
86. We also have to permit the
87 key as part of the strong parameter, in
09:
0 and in
51:
1 Within the
54 model, after running a migration to add a
80 column using
92 command, you would add:
2 and in the
23 model:
3 Then, in our
04 action template (
96 method to avoid displaying any article that is archived:
4 Similarly, in our comment partial view (
96 method to avoid displaying any comment that is archived:
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)
99. We can create a new file inside
00 called
01 , and store all of the status methods that were duplicated in the models.
02
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
03 (API Guide) gives us a simpler way to include them:
7 Now, we can remove the duplicated logic from each model and instead include our new
99 module: In
35:
8 and in
24:
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:
0 Then in the view, you can call it like any class method:
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
77 if it hasn't been set yet. In
94, we can add:
2 and in
69:
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
06 action in the
43. So first, let's add the delete link in the
62 partial:
4 Clicking this new "Destroy Comment" link will fire off a
13 to our
43, which can then use this to find the comment we want to delete, so let's add a
06 action to our controller (
51):
5 The
06 action will find the article we are looking at, locate the comment within the
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
19 option of an association to achieve this. Modify the Article model,
35, as follows:
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
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
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
05 in
09. In our case, we want the user to be authenticated on every action except
04 and
89, so we write that:
7 We also want to allow only authenticated users to delete comments, so in the
43 (
8 Now if you try to create a new article, you will be greeted with a basic HTTP Authentication challenge: 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 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:
FeedbackYou'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. |