Now that you've seen how to create a controller, an action and a view, let's create something with a bit more substance.
In the Blog application, you will now create a new resource. A resource is the term used for a collection of similar objects, such as articles, people or animals. You can create, read, update and destroy items for a resource and these operations are referred to as CRUD operations.
Rails provides a resources method which can be used to declare a standard REST resource. You need to add the article resource to the config/routes.rb so the file will look as follows:
Rails.application.routes.draw doget 'welcome/index'resources :articlesroot 'welcome#index'end
If you run bin/rails routes (or bin/rake routes for older versions), you'll see that it has defined routes for all the standard RESTful actions. The meaning of the prefix column (and other columns) will be seen later, but for now notice that Rails has inferred the singular form article and makes meaningful use of the distinction.
Prefix Verb URI Pattern Controller#Actionwelcome_index GET /welcome/index(.:format) welcome#indexarticles GET /articles(.:format) articles#indexPOST /articles(.:format) articles#createnew_article GET /articles/new(.:format) articles#newedit_article GET /articles/:id/edit(.:format) articles#editarticle GET /articles/:id(.:format) articles#showPATCH /articles/:id(.:format) articles#updatePUT /articles/:id(.:format) articles#updateDELETE /articles/:id(.:format) articles#destroyroot GET / welcome#indexrails_service_blob GET /rails/active_storage/blobs/:signed_id/*filename(.:format) active_storage/blobs#showrails_blob_representation GET /rails/active_storage/representations/:signed_blob_id/:variation_key/*filename(.:format) active_storage/representations#showrails_disk_service GET /rails/active_storage/disk/:encoded_key/*filename(.:format) active_storage/disk#showupdate_rails_disk_service PUT /rails/active_storage/disk/:encoded_token(.:format) active_storage/disk#updaterails_direct_uploads POST /rails/active_storage/direct_uploads(.:format) active_storage/direct_uploads#create
In the next section, you will add the ability to create new articles in your application and be able to view them. This is the "C" and the "R" from CRUD: create and read. The form for doing this will look like this:
It will look a little basic for now, but that's ok. We'll look at improving the styling for it afterwards.
Laying down the groundwork
Firstly, you need a place within the application to create a new article. A great place for that would be at /articles/new. With the route already defined, requests can now be made to /articles/new in the application. Navigate to http://localhost:3000/articles/new and you'll see a routing error:
This error occurs because the route needs to have a controller defined in order to serve the request. The solution to this particular problem is simple: create a controller called ArticlesController. You can do this by running this command:
$ bin/rails generate controller Articles
If you open up the newly generated app/controllers/articles_controller.rb you'll see a fairly empty controller:
class ArticlesController < ApplicationControllerend
A controller is simply a class that is defined to inherit from ApplicationController. It's inside this class that you'll define methods that will become the actions for this controller. These actions will perform CRUD operations on the articles within our system.
Note that there are public, private and protected methods in Ruby, but only public methods can be actions for controllers.
If you refresh http://localhost:3000/articles/new now, you'll get a new error:
This error indicates that Rails cannot find the new action inside the ArticlesController that you just generated. This is because when controllers are generated in Rails they are empty by default, unless you tell it your desired actions during the generation process.
To manually define an action inside a controller, all you need to do is to define a new method inside the controller. Open app/controllers/articles_controller.rb and inside the ArticlesController class, define the new method so that your controller now looks like this:
class ArticlesController < ApplicationControllerdef newendend
With the new method defined in ArticlesController, if you refresh http://localhost:3000/articles/new you'll see another error:
You're getting this error now because Rails expects plain actions like this one to have views associated with them to display their information. With no view available, Rails will raise an exception.
Let's look at the full error message again:
ArticlesController#new is missing a template for this request format and variant. request.formats: ["text/html"] request.variant: [] NOTE! For XHR/Ajax or API requests, this action would normally respond with 204 No Content: an empty white screen. Since you're loading it in a web browser, we assume that you expected to actually render a template, not… nothing, so we're showing an error to be extra-clear. If you expect 204 No Content, carry on. That's what you'll get from an XHR or API request. Give it a shot.
That's quite a lot of text! Let's quickly go through and understand what each part of it means.
The first part identifies which template is missing. In this case, it's the articles/new template. Rails will first look for this template. If not found, then it will attempt to load a template called application/new. It looks for one here because the ArticlesController inherits from ApplicationController.
The next part of the message contains request.formats which specifies the format of template to be served in response. It is set to text/html as we requested this page via browser, so Rails is looking for an HTML template. request.variant specifies what kind of physical devices would be served by the response and helps Rails determine which template to use in the response. It is empty because no information has been provided.
The simplest template that would work in this case would be one located at app/views/articles/new.html.erb. The extension of this file name is important: the first extension is the format of the template, and the second extension is the handler that will be used to render the template. Rails is attempting to find a template called articles/new within app/viewsfor the application. The format for this template can only be html and the default handler for HTML is erb. Rails uses other handlers for other formats. builder handler is used to build XML templates and coffee handler uses CoffeeScript to build JavaScript templates. Since you want to create a new HTML form, you will be using the ERB language which is designed to embed Ruby in HTML.
Therefore the file should be called articles/new.html.erb and needs to be located inside the app/views directory of the application.
Go ahead now and create a new file at app/views/articles/new.html.erb and write this content in it:
<h1>New Article</h1>
When you refresh http://localhost:3000/articles/new you'll now see that the page has a title. The route, controller, action and view are now working harmoniously! It's time to create the form for a new article.
The first form
To create a form within this template, you will use a form builder. The primary form builder for Rails is provided by a helper method called form_with. To use this method, add this code into app/views/articles/new.html.erb:
<%= form_with scope: :article, local: true do |form| %><p><%= form.label :title %><br><%= form.text_field :title %></p><p><%= form.label :text %><br><%= form.text_area :text %></p><p><%= form.submit %></p><% end %>
If you refresh the page now, you'll see the exact same form from our example above. Building forms in Rails is really just that easy!
When you call form_with, you pass it an identifying scope for this form. In this case, it's the symbol :article. This tells the form_with helper what this form is for. Inside the block for this method, the FormBuilder object - represented by form - is used to build two labels and two text fields, one each for the title and text of an article. Finally, a call to submit on the form object will create a submit button for the form.
There's one problem with this form though. If you inspect the HTML that is generated, by viewing the source of the page, you will see that the action attribute for the form is pointing at /articles/new. This is a problem because this route goes to the very page that you're on right at the moment, and that route should only be used to display the form for a new article.
The form needs to use a different URL in order to go somewhere else. This can be done quite simply with the :url option of form_with. Typically in Rails, the action that is used for new form submissions like this is called "create", and so the form should be pointed to that action.
Edit the form_with line inside app/views/articles/new.html.erb to look like this:
<%= form_with scope: :article, url: articles_path, local: true do |form| %>
In this example, the articles_path helper is passed to the :url option. To see what Rails will do with this, we look back at the output of bin/rails routes:
$ bin/rails routesPrefix Verb URI Pattern Controller#Actionwelcome_index GET /welcome/index(.:format) welcome#indexarticles GET /articles(.:format) articles#indexPOST /articles(.:format) articles#createnew_article GET /articles/new(.:format) articles#newedit_article GET /articles/:id/edit(.:format) articles#editarticle GET /articles/:id(.:format) articles#showPATCH /articles/:id(.:format) articles#updatePUT /articles/:id(.:format) articles#updateDELETE /articles/:id(.:format) articles#destroy...
The articles_path helper tells Rails to point the form to the URI Pattern associated with the articles prefix; and the form will (by default) send a POST request to that route. This is associated with the create action of the current controller, the ArticlesController.
With the form and its associated route defined, you will be able to fill in the form and then click the submit button to begin the process of creating a new article, so go ahead and do that. When you submit the form, you should see a familiar error:
You now need to create the create action within the ArticlesController for this to work.
By default form_with submits forms using Ajax thereby skipping full page redirects. To make this guide easier to get into we've disabled that with local: true for now.
Creating articles
To make the "Unknown action" go away, you can define a create action within the ArticlesController class in app/controllers/articles_controller.rb, underneath the new action, as shown:
class ArticlesController < ApplicationControllerdef newenddef createendend
If you re-submit the form now, you may not see any change on the page. Don't worry! This is because Rails by default returns 204 No Content response for an action if we don't specify what the response should be. We just added the create action but didn't specify anything about how the response should be. In this case, the create action should save our new article to the database.
When a form is submitted, the fields of the form are sent to Rails as parameters. These parameters can then be referenced inside the controller actions, typically to perform a particular task. To see what these parameters look like, change the create action to this:
def createrender plain: params[:article].inspectend
The render method here is taking a very simple hash with a key of :plain and value of params[:article].inspect. The params method is the object which represents the parameters (or fields) coming in from the form. The params method returns an ActionController::Parameters object, which allows you to access the keys of the hash using either strings or symbols. In this situation, the only parameters that matter are the ones from the form.
Ensure you have a firm grasp of the params method, as you'll use it fairly regularly. Let's consider an example URL: http://www.example.com/?username=dhh&email=dhh@email.com. In this URL, params[:username] would equal "dhh" and params[:email] would equal "dhh@email.com".
If you re-submit the form one more time, you'll see something that looks like the following:
<ActionController::Parameters {"title"=>"First Article!", "text"=>"This is my first article."} permitted: false>
This action is now displaying the parameters for the article that are coming in from the form. However, this isn't really all that helpful. Yes, you can see the parameters but nothing in particular is being done with them.
Creating the Article model
Models in Rails use a singular name, and their corresponding database tables use a plural name. Rails provides a generator for creating models, which most Rails developers tend to use when creating new models. To create the new model, run this command in your terminal:
$ bin/rails generate model Article title:string text:text
With that command we told Rails that we want an Article model, together with a title attribute of type string, and a text attribute of type text. Those attributes are automatically added to the articles table in the database and mapped to the Article model.
Rails responded by creating a bunch of files. For now, we're only interested in app/models/article.rb and db/migrate/20180829004036_create_articles.rb (your name could be a bit different). The latter is responsible for creating the database structure, which is what we'll look at next.
Active Record is smart enough to automatically map column names to model attributes, which means you don't have to declare attributes inside Rails models, as that will be done automatically by Active Record.
Running a Migration
As we've just seen, bin/rails generate model created a database migration file inside the db/migrate directory. Migrations are Ruby classes that are designed to make it simple to create and modify database tables. Rails uses rake commands to run migrations, and it's possible to undo a migration after it's been applied to your database. Migration filenames include a timestamp to ensure that they're processed in the order that they were created.
If you look in the db/migrate/YYYYMMDDHHMMSS_create_articles.rb file (remember, yours will have a slightly different name), here's what you'll find:
class CreateArticles < ActiveRecord::Migration[5.2]def changecreate_table :articles do |t|t.string :titlet.text :textt.timestampsendendend
The above migration creates a method named change which will be called when you run this migration. The action defined in this method is also reversible, which means Rails knows how to reverse the change made by this migration, in case you want to reverse it later. When you run this migration it will create an articles table with one string column and a text column. It also creates two timestamp fields to allow Rails to track article creation and update times.
For more information about migrations, refer to Active Record Migrations.
At this point, you can use a bin/rails command to run the migration:
$ bin/rails db:migrate
Rails will execute this migration command and tell you it created the Articles table.
== 20180829004036 CreateArticles: migrating ===================================-- create_table(:articles)-> 0.0145s== 20180829004036 CreateArticles: migrated (0.0145s) ==========================
Because you're working in the development environment by default, this command will apply to the database defined in the development section of your config/database.yml file. If you would like to execute migrations in another environment, for instance in production, you must explicitly pass it when invoking the command: bin/rails db:migrate RAILS_ENV=production.
Saving data in the controller
Back in ArticlesController, we need to change the create action to use the new Articlemodel to save the data in the database. Open app/controllers/articles_controller.rb and change the create action to look like this:
def create@article = Article.new(params[:article])@article.saveredirect_to @articleend
Here's what's going on: every Rails model can be initialized with its respective attributes, which are automatically mapped to the respective database columns. In the first line we do just that (remember that params[:article] contains the attributes we're interested in). Then, @article.save is responsible for saving the model in the database. Finally, we redirect the user to the show action, which we'll define later.
You might be wondering why the A in Article.new is capitalized above, whereas most other references to articles in this guide have used lowercase. In this context, we are referring to the class named Article that is defined in app/models/article.rb. Class names in Ruby must begin with a capital letter.
As we'll see later, @article.save returns a boolean indicating whether the article was saved or not.
If you now go to http://localhost:3000/articles/new you'll almost be able to create an article. Try it! You should get an error that looks like this:
Rails has several security features that help you write secure applications, and you're running into one of them now. This one is called strong parameters, which requires us to tell Rails exactly which parameters are allowed into our controller actions.
Why do you have to bother? The ability to grab and automatically assign all controller parameters to your model in one shot makes the programmer's job easier, but this convenience also allows malicious use. What if a request to the server was crafted to look like a new article form submit but also included extra fields with values that violated your application's integrity? They would be 'mass assigned' into your model and then into the database along with the good stuff - potentially breaking your application or worse.
We have to whitelist our controller parameters to prevent wrongful mass assignment. In this case, we want to both allow and require the title and text parameters for valid use of create. The syntax for this introduces require and permit. The change will involve one line in the create action:
@article = Article.new(params.require(:article).permit(:title, :text))
This is often factored out into its own method so it can be reused by multiple actions in the same controller, for example create and update. Above and beyond mass assignment issues, the method is often made private to make sure it can't be called outside its intended context. Here is the result:
def create@article = Article.new(article_params)@article.saveredirect_to @articleendprivate def article_paramsparams.require(:article).permit(:title, :text)end