One place for hosting & domains

      Resources

      How To Create Nested Resources for a Ruby on Rails Application


      Introduction

      Ruby on Rails is a web application framework written in Ruby that offers developers an opinionated approach to application development. Working with Rails gives developers:

      • Conventions for handling things like routing, stateful data, and asset management.
      • A firm grounding in the model-view-controller (MCV) architectural pattern, which separates an application’s logic, located in models, from the presentation and routing of application information.

      As you add complexity to your Rails applications, you will likely work with multiple models, which represent your application’s business logic and interface with your database. Adding related models means establishing meaningful relationships between them, which then affect how information gets relayed through your application’s controllers, and how it is captured and presented back to users through views.

      In this tutorial, you will build on an existing Rails application that offers users facts about sharks. This application already has a model for handling shark data, but you will add a nested resource for posts about individual sharks. This will allow users to build out a wider body of thoughts and opinions about individual sharks.

      Prerequisites

      To follow this tutorial, you will need:

      • A local machine or development server running Ubuntu 18.04. Your development machine should have a non-root user with administrative privileges and a firewall configured with ufw. For instructions on how to set this up, see our Initial Server Setup with Ubuntu 18.04 tutorial.
      • Node.js and npm installed on your local machine or development server. This tutorial uses Node.js version 10.16.3 and npm version 6.9.0. For guidance on installing Node.js and npm on Ubuntu 18.04, follow the instructions in the “Installing Using a PPA” section of How To Install Node.js on Ubuntu 18.04.
      • Ruby, rbenv, and Rails installed on your local machine or development server, following Steps 1-4 in How To Install Ruby on Rails with rbenv on Ubuntu 18.04. This tutorial uses Ruby 2.5.1, rbenv 1.1.2, and Rails 5.2.3.
      • SQLite installed, and a basic shark information application created, following the directions in How To Build a Ruby on Rails Application.

      Step 1 — Scaffolding the Nested Model

      Our application will take advantage of Active Record associations to build out a relationship between Shark and Post models: posts will belong to particular sharks, and each shark can have multiple posts. Our Shark and Post models will therefore be related through belongs_to and has_many associations.

      The first step to building out the application in this way will be to create a Post model and related resources. To do this, we can use the rails generate scaffold command, which will give us a model, a database migration to alter the database schema, a controller, a full set of views to manage standard Create, Read, Update, and Delete (CRUD) operations, and templates for partials, helpers, and tests. We will need to modify these resources, but using the scaffold command will save us some time and energy since it generates a structure we can use as a starting point.

      First, make sure that you are in the sharkapp directory for the Rails project that you created in the prerequisites:

      Create your Post resources with the following command:

      • rails generate scaffold Post body:text shark:references

      With body:text, we’re telling Rails to include a body field in the posts database table — the table that maps to the Post model. We’re also including the :references keyword, which sets up an association between the Shark and Post models. Specifically, this will ensure that a foreign key representing each shark entry in the sharks database is added to the posts database.

      Once you have run the command, you will see output confirming the resources that Rails has generated for the application. Before moving on, you can check your database migration file to look at the relationship that now exists between your models and database tables. Use the following command to look at the contents of the file, making sure to substitute the timestamp on your own migration file for what’s shown here:

      • cat db/migrate/20190805132506_create_posts.rb

      You will see the following output:

      Output

      class CreatePosts < ActiveRecord::Migration[5.2] def change create_table :posts do |t| t.text :body t.references :shark, foreign_key: true t.timestamps end end end

      As you can see, the table includes a column for a shark foreign key. This key will take the form of model_name_id — in our case, shark_id.

      Rails has established the relationship between the models elsewhere as well. Take a look at the newly generated Post model with the following command:

      Output

      class Post < ApplicationRecord belongs_to :shark end

      The belongs_to association sets up a relationship between models in which a single instance of the declaring model belongs to a single instance of the named model. In the case of our application, this means that a single post belongs to a single shark.

      In addition to setting this relationship, the rails generate scaffold command also created routes and views for posts, as it did for our shark resources in Step 3 of How To Build a Ruby on Rails Application.

      This is a useful start, but we will need to configure some additional routing and solidify the Active Record association for the Shark model in order for the relationship between our models and routes to work as desired.

      Step 2 — Specifying Nested Routes and Associations for the Parent Model

      Rails has already set the belongs_to association in our Post model, thanks to the :references keyword in the rails generate scaffold command, but in order for that relationship to function properly we will need to specify a has_many association in our Shark model as well. We will also need to make changes to the default routing that Rails gave us in order to make post resources the children of shark resources.

      To add the has_many association to the Shark model, open app/models/shark.rb using nano or your favorite editor:

      Add the following line to the file to establish the relationship between sharks and posts:

      ~/sharkapp/app/models/shark.rb

      class Shark < ApplicationRecord
        has_many :posts
        validates :name, presence: true, uniqueness: true
        validates :facts, presence: true
      end
      

      One thing that is worth thinking about here is what happens to posts once a particular shark is deleted. We likely do not want the posts associated with a deleted shark persisting in the database. To ensure that any posts associated with a given shark are eliminated when that shark is deleted, we can include the dependent option with the association.

      Add the following code to the file to ensure that the destroy action on a given shark deletes any associated posts:

      ~/sharkapp/app/models/post.rb

      class Shark < ApplicationRecord
        has_many :posts , dependent: :destroy
        validates :name, presence: true, uniqueness: true
        validates :facts, presence: true
      end
      

      Once you have finished making these changes, save and close the file. If you are using nano, you can do this by pressing CTRL+X, Y, then ENTER.

      Next, open your config/routes.rb file to modify the relationship between your resourceful routes:

      Currently, the file looks like this:

      ~/sharkapp/config/routes.rb

      Rails.application.routes.draw do
        resources :posts 
        resources :sharks
      
        root 'sharks#index'
        # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
      end
      

      The current code establishes an independent relationship between our routes, when what we would like to express is a dependent relationship between sharks and their associated posts.

      Let’s update our route declaration to make :sharks the parent of :posts. Update the code in the file to look like the following:

      ~/sharkapp/config/routes.rb

      Rails.application.routes.draw do
        resources :sharks do
          resources :posts
        end
        root 'sharks#index'
        # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
      end
      

      Save and close the file when you are finished editing.

      With these changes in place, you can move on to updating your posts controller.

      Step 3 — Updating the Posts Controller

      The association between our models gives us methods that we can use to create new post instances associated with particular sharks. To use these methods, we will need to add them our posts controller.

      Open the posts controller file:

      • nano app/controllers/posts_controller.rb

      Currently, the file looks like this:

      ~/sharkapp/controllers/posts_controller.rb

      class PostsController < ApplicationController
        before_action :set_post, only: [:show, :edit, :update, :destroy]
      
        # GET /posts
        # GET /posts.json
        def index
          @posts = Post.all
        end
      
        # GET /posts/1
        # GET /posts/1.json
        def show
        end
      
        # GET /posts/new
        def new
          @post = Post.new
        end
      
        # GET /posts/1/edit
        def edit
        end
      
        # POST /posts
        # POST /posts.json
        def create
          @post = Post.new(post_params)
      
          respond_to do |format|
            if @post.save
              format.html { redirect_to @post, notice: 'Post was successfully created.' }
              format.json { render :show, status: :created, location: @post }
            else
              format.html { render :new }
              format.json { render json: @post.errors, status: :unprocessable_entity }
            end
          end
        end
      
        # PATCH/PUT /posts/1
        # PATCH/PUT /posts/1.json
        def update
          respond_to do |format|
            if @post.update(post_params)
              format.html { redirect_to @post, notice: 'Post was successfully updated.' }
              format.json { render :show, status: :ok, location: @post }
            else
              format.html { render :edit }
              format.json { render json: @post.errors, status: :unprocessable_entity }
            end
          end
        end
      
        # DELETE /posts/1
        # DELETE /posts/1.json
        def destroy
          @post.destroy
          respond_to do |format|
            format.html { redirect_to posts_url, notice: 'Post was successfully destroyed.' }
            format.json { head :no_content }
          end
        end
      
        private
          # Use callbacks to share common setup or constraints between actions.
          def set_post
            @post = Post.find(params[:id])
          end
      
          # Never trust parameters from the scary internet, only allow the white list through.
          def post_params
            params.require(:post).permit(:body, :shark_id)
          end
      end
      

      Like our sharks controller, this controller’s methods work with instances of the associated Post class. For example, the new method creates a new instance of the Post class, the index method grabs all instances of the class, and the set_post method uses find and params to select a particular post by id. If, however, we want our post instances to be associated with particular shark instances, then we will need to modify this code, since the Post class is currently operating as an independent entity.

      Our modifications will make use of two things:

      • The methods that became available to us when we added the belongs_to and has_many associations to our models. Specifically, we now have access to the build method thanks to the has_many association we defined in our Shark model. This method will allow us to create a collection of post objects associated with a particular shark object, using the shark_id foreign key that exists in our posts database.
      • The routes and routing helpers that became available when we created a nested posts route. For a full list of example routes that become available when you create nested relationships between resources, see the Rails documentation. For now, it will be enough for us to know that for each specific shark — say sharks/1 — there will be an associated route for posts related to that shark: sharks/1/posts. There will also be routing helpers like shark_posts_path(@shark) and edit_sharks_posts_path(@shark) that refer to these nested routes.

      In the file, we’ll begin by writing a method, get_shark, that will run before each action in the controller. This method will create a local @shark instance variable by finding a shark instance by shark_id. With this variable available to us in the file, it will be possible to relate posts to a specific shark in the other methods.

      Above the other private methods at the bottom of the file, add the following method:

      ~/sharkapp/controllers/posts_controller.rb

      . . . 
      private
        def get_shark
          @shark = Shark.find(params[:shark_id])
        end
        # Use callbacks to share common setup or constraints between actions.
      . . . 
      

      Next, add the corresponding filter to the top of the file, before the existing filter:

      ~/sharkapp/controllers/posts_controller.rb

      class PostsController < ApplicationController
        before_action :get_shark
      

      This will ensure that get_shark runs before each action defined in the file.

      Next, you can use this @shark instance to rewrite the index method. Instead of grabbing all instances of the Post class, we want this method to return all post instances associated with a particular shark instance.

      Modify the index method to look like this:

      ~/sharkapp/controllers/posts_controller.rb

      . . .
        def index
          @posts = @shark.posts
        end
      . . .
      

      The new method will need a similar revision, since we want a new post instance to be associated with a particular shark. To achieve this, we can make use of the build method, along with our local @shark instance variable.

      Change the new method to look like this:

      ~/sharkapp/controllers/posts_controller.rb

      . . . 
        def new
          @post = @shark.posts.build
        end
      . . . 
      

      This method creates a post object that’s associated with the specific shark instance from the get_shark method.

      Next, we’ll address the method that’s most closely tied to new: create. The create method does two things: it builds a new post instance using the parameters that users have entered into the new form, and, if there are no errors, it saves that instance and uses a route helper to redirect users to where they can see the new post. In the case of errors, it renders the new template again.

      Update the create method to look like this:

      ~/sharkapp/controllers/posts_controller.rb

        def create
          @post = @shark.posts.build(post_params)
      
              respond_to do |format|
               if @post.save  
                  format.html { redirect_to shark_posts_path(@shark), notice: 'Post was successfully created.' }
                  format.json { render :show, status: :created, location: @post }
               else
                  format.html { render :new }
                  format.json { render json: @post.errors, status: :unprocessable_entity }
            end
          end
        end
      

      Next, take a look at the update method. This method uses a @post instance variable, which is not explicitly set in the method itself. Where does this variable come from?

      Take a look at the filters at the top of the file. The second, auto-generated before_action filter provides an answer:

      ~/sharkapp/controllers/posts_controller.rb

      class PostsController < ApplicationController
        before_action :get_shark
        before_action :set_post, only: [:show, :edit, :update, :destroy]
        . . .
      

      The update method (like show, edit, and destroy) takes a @post variable from the set_post method. That method, listed under the get_shark method with our other private methods, currently looks like this:

      ~/sharkapp/controllers/posts_controller.rb

      . . . 
      private
      . . . 
        def set_post
          @post = Post.find(params[:id])
        end
      . . .
      

      In keeping with the methods we’ve used elsewhere in the file, we will need to modify this method so that @post refers to a particular instance in the collection of posts that’s associated with a particular shark. Keep the build method in mind here — thanks to the associations between our models, and the methods (like build) that are available to us by virtue of those associations, each of our post instances is part of a collection of objects that’s associated with a particular shark. So it makes sense that when querying for a particular post, we would query the collection of posts associated with a particular shark.

      Update set_post to look like this:

      ~/sharkapp/controllers/posts_controller.rb

      . . . 
      private
      . . . 
        def set_post
          @post = @shark.posts.find(params[:id])
        end
      . . .
      

      Instead of finding a particular instance of the entire Post class by id, we instead search for a matching id in the collection of posts associated with a particular shark.

      With that method updated, we can look at the update and destroy methods.

      The update method makes use of the @post instance variable from set_post, and uses it with the post_params that the user has entered in the edit form. In the case of success, we want Rails to send the user back to the index view of the posts associated with a particular shark. In the case of errors, Rails will render the edit template again.

      In this case, the only change we will need to make is to the redirect_to statement, to handle successful updates. Update it to redirect to shark_post_path(@shark), which will redirect to the index view of the selected shark’s posts:

      ~/sharkapp/controllers/posts_controller.rb

      . . . 
        def update
          respond_to do |format|
            if @post.update(post_params)
              format.html { redirect_to shark_post_path(@shark), notice: 'Post was successfully updated.' }
              format.json { render :show, status: :ok, location: @post }
            else
              format.html { render :edit }
              format.json { render json: @post.errors, status: :unprocessable_entity }
            end
          end
        end
      . . .
      

      Next, we will make a similar change to the destroy method. Update the redirect_to method to redirect requests to shark_posts_path(@shark) in the case of success:

      ~/sharkapp/controllers/posts_controller.rb

      . . . 
        def destroy
          @post.destroy
           respond_to do |format|
            format.html { redirect_to shark_posts_path(@shark), notice: 'Post was successfully destroyed.' }
            format.json { head :no_content }
          end
        end
      . . .
      

      This is the last change we will make. You now have a posts controller file that looks like this:

      ~/sharkapp/controllers/posts_controller.rb

      class PostsController < ApplicationController
        before_action :get_shark
        before_action :set_post, only: [:show, :edit, :update, :destroy]
      
        # GET /posts
        # GET /posts.json
        def index
          @posts = @shark.posts
        end
      
        # GET /posts/1
        # GET /posts/1.json
        def show
        end
      
        # GET /posts/new
        def new
          @post = @shark.posts.build
        end
      
        # GET /posts/1/edit
        def edit
        end
      
        # POST /posts
        # POST /posts.json
        def create
          @post = @shark.posts.build(post_params)
      
              respond_to do |format|
               if @post.save  
                  format.html { redirect_to shark_posts_path(@shark), notice: 'Post was successfully created.' }
                  format.json { render :show, status: :created, location: @post }
               else
                  format.html { render :new }
                  format.json { render json: @post.errors, status: :unprocessable_entity }
            end
          end
        end
      
        # PATCH/PUT /posts/1
        # PATCH/PUT /posts/1.json
        def update
          respond_to do |format|
            if @post.update(post_params)
              format.html { redirect_to shark_post_path(@shark), notice: 'Post was successfully updated.' }
              format.json { render :show, status: :ok, location: @post }
            else
              format.html { render :edit }
              format.json { render json: @post.errors, status: :unprocessable_entity }
            end
          end
        end
      
        # DELETE /posts/1
        # DELETE /posts/1.json
        def destroy
          @post.destroy
          respond_to do |format|
            format.html { redirect_to shark_posts_path(@shark), notice: 'Post was successfully destroyed.' }
            format.json { head :no_content }
          end
        end
      
        private
      
         def get_shark
           @shark = Shark.find(params[:shark_id])
         end
          # Use callbacks to share common setup or constraints between actions.
          def set_post
            @post = @shark.posts.find(params[:id])
          end
      
          # Never trust parameters from the scary internet, only allow the white list through.
          def post_params
            params.require(:post).permit(:body, :shark_id)
          end
      end
      

      The controller manages how information is passed from the view templates to the database and vice versa. Our controller now reflects the relationship between our Shark and Post models, in which posts are associated with particular sharks. We can move on to modifying the view templates themselves, which are where users will pass in and modify post information about particular sharks.

      Step 4 — Modifying Views

      Our view template revisions will involve changing the templates that relate to posts, and also modifying our sharks show view, since we want users to see the posts associated with particular sharks.

      Let’s start with the foundational template for our posts: the form partial that is reused across multiple post templates. Open that form now:

      • nano app/views/posts/_form.html.erb

      Rather than passing only the post model to the form_with form helper, we will pass both the shark and post models, with post set as a child resource.

      Change the first line of the file to look like this, reflecting the relationship between our shark and post resources:

      ~/sharkapp/views/posts/_form.html.erb

      <%= form_with(model: [@shark, post], local: true) do |form| %>
      . . . 
      

      Next, delete the section that lists the shark_id of the related shark, since this is not essential information in the view.

      The finished form, complete with our edits to the first line and without the deleted shark_id section, will look like this:

      ~/sharkapp/views/posts/_form.html.erb

      <%= form_with(model: [@shark, post], local: true) do |form| %>
        <% if post.errors.any? %>
          <div id="error_explanation">
            <h2><%= pluralize(post.errors.count, "error") %> prohibited this post from being saved:</h2>
      
            <ul>
            <% post.errors.full_messages.each do |message| %>
              <li><%= message %></li>
            <% end %>
            </ul>
          </div>
        <% end %>
      
        <div class="field">
          <%= form.label :body %>
          <%= form.text_area :body %>
        </div>
      
        <div class="actions">
          <%= form.submit %>
        </div>
      <% end %>
      

      Save and close the file when you are finished editing.

      Next, open the index view, which will show the posts associated with a particular shark:

      • nano app/views/posts/index.html.erb

      Thanks to the rails generate scaffold command, Rails has generated the better part of the template, complete with a table that shows the body field of each post and its associated shark.

      Much like the other code we have already modified, however, this template treats posts as independent entities, when we would like to make use of the associations between our models and the collections and helper methods that these associations give us.

      In the body of the table, make the following updates:

      First, update post.shark to post.shark.name, so that the table will include the name field of the associated shark, rather than identifying information about the shark object itself:

      ~/sharkapp/app/views/posts/index.html.erb

      . . . 
        <tbody>
          <% @posts.each do |post| %>
            <tr>
              <td><%= post.body %></td>
              <td><%= post.shark.name %></td>
      . . . 
      

      Next, change the Show redirect to direct users to the show view for the associated shark, since they will most likely want a way to navigate back to the original shark. We can make use of the @shark instance variable that we set in the controller here, since Rails makes instance variables created in the controller available to all views. We’ll also change the text for the link from Show to Show Shark, so that users will better understand its function.

      Update the this line to the following:

      ~/sharkapp/app/views/posts/index.html.erb

      . . . 
        <tbody>
          <% @posts.each do |post| %>
            <tr>
              <td><%= post.body %></td>
              <td><%= post.shark.name %></td>
              <td><%= link_to 'Show Shark', [@shark] %></td>
      

      In the next line, we want to ensure that users are routed the right nested path when they go to edit a post. This means that rather than being directed to posts/post_id/edit, users will be directed to sharks/shark_id/posts/post_id/edit. To do this, we’ll use the shark_post_path routing helper and our models, which Rails will treat as URLs. We’ll also update the link text to make its function clearer.

      Update the Edit line to look like the following:

      ~/sharkapp/app/views/posts/index.html.erb

      . . . 
        <tbody>
          <% @posts.each do |post| %>
            <tr>
              <td><%= post.body %></td>
              <td><%= post.shark.name %></td>
              <td><%= link_to 'Show Shark', [@shark] %></td>
              <td><%= link_to 'Edit Post', edit_shark_post_path(@shark, post) %></td>
      

      Next, let’s add a similar change to the Destroy link, updating its function in the string, and adding our shark and post resources:

      ~/sharkapp/app/views/posts/index.html.erb

      . . . 
        <tbody>
          <% @posts.each do |post| %>
            <tr>
              <td><%= post.body %></td>
              <td><%= post.shark.name %></td>
              <td><%= link_to 'Show Shark', [@shark] %></td>
              <td><%= link_to 'Edit Post', edit_shark_post_path(@shark, post) %></td>
              <td><%= link_to 'Destroy Post', [@shark, post], method: :delete, data: { confirm: 'Are you sure?' } %></td>
      

      Finally, at the bottom of the form, we will want to update the New Post path to take users to the appropriate nested path when they want to create a new post. Update the last line of the file to make use of the new_shark_post_path(@shark) routing helper:

      ~/sharkapp/app/views/posts/index.html.erb

      . . . 
      <%= link_to 'New Post', new_shark_post_path(@shark) %>
      

      The finished file will look like this:

      ~/sharkapp/app/views/posts/index.html.erb

      <p id="notice"><%= notice %></p>
      
      <h1>Posts</h1>
      
      <table>
        <thead>
          <tr>
            <th>Body</th>
            <th>Shark</th>
            <th colspan="3"></th>
          </tr>
        </thead>
      
        <tbody>
          <% @posts.each do |post| %>
            <tr>
              <td><%= post.body %></td>
              <td><%= post.shark.name %></td>
              <td><%= link_to 'Show Shark', [@shark] %></td>
              <td><%= link_to 'Edit Post', edit_shark_post_path(@shark, post) %></td>
              <td><%= link_to 'Destroy Post', [@shark, post], method: :delete, data: { confirm: 'Are you sure?' } %></td>
            </tr>
          <% end %>
        </tbody>
      </table>
      
      <br>
      
      <%= link_to 'New Post', new_shark_post_path(@shark) %>
      

      Save and close the file when you are finished editing.

      The other edits we will make to post views won’t be as numerous, since our other views use the form partial we have already edited. However, we will want to update the link_to references in the other post templates to reflect the changes we have made to our form partial.

      Open app/views/posts/new.html.erb:

      • nano app/views/posts/new.html.erb

      Update the link_to reference at the bottom of the file to make use of the shark_posts_path(@shark) helper:

      ~/sharkapp/app/views/posts/new.html.erb

      . . . 
      <%= link_to 'Back', shark_posts_path(@shark) %>
      

      Save and close the file when you are finished making this change.

      Next, open the edit template:

      • nano app/views/posts/edit.html.erb

      In addition to the Back path, we’ll update Show to reflect our nested resources. Change the last two lines of the file to look like this:

      ~/sharkapp/app/views/posts/edit.html.erb

      . . . 
      <%= link_to 'Show', [@shark, @post] %> |
      <%= link_to 'Back', shark_posts_path(@shark) %>
      

      Save and close the file.

      Next, open the show template:

      • nano app/views/posts/show.html.erb

      Make the following edits to the Edit and Back paths at the bottom of the file:

      ~/sharkapp/app/views/posts/edit.html.erb

      . . .
      <%= link_to 'Edit', edit_shark_post_path(@shark, @post) %> |
      <%= link_to 'Back', shark_posts_path(@shark) %>
      

      Save and close the file when you are finished.

      As a final step, we will want to update the show view for our sharks so that posts are visible for individual sharks. Open that file now:

      • nano app/views/sharks/show.html.erb

      Our edits here will include adding a Posts section to the form and an Add Post link at the bottom of the file.

      Below the Facts for a given shark, we will add a new section that iterates through each instance in the collection of posts associated with this shark, outputting the body of each post.

      Add the following code below the Facts section of the form, and above the redirects at the bottom of the file:

      ~/sharkapp/app/views/sharks/show.html.erb

      . . .
      <p>
        <strong>Facts:</strong>
        <%= @shark.facts %>
      </p>
      
      <h2>Posts</h2>
      <% for post in @shark.posts %>
          <ul>
            <li><%= post.body %></li>
        </ul>
      <% end %>
      
      <%= link_to 'Edit', edit_shark_path(@shark) %> |
      . . . 
      

      Next, add a new redirect to allow users to add a new post for this particular shark:

      ~/sharkapp/app/views/sharks/show.html.erb

      . . .
      <%= link_to 'Edit', edit_shark_path(@shark) %> |
      <%= link_to 'Add Post', shark_posts_path(@shark) %> |
      <%= link_to 'Back', sharks_path %>
      

      Save and close the file when you are finished editing.

      You have now made changes to your application’s models, controllers, and views to ensure that posts are always associated with a particular shark. As a final step, we can add some validations to our Post model to guarantee consistency in the data that’s saved to the database.

      Step 5 — Adding Validations and Testing the Application

      In Step 5 of How To Build a Ruby on Rails Application, you added validations to your Shark model to ensure uniformity and consistency in the data that gets saved to the sharks database. We’ll now take a similar step to ensure guarantees for the posts database as well.

      Open the file where your Post model is defined:

      Here, we want to ensure that posts are not blank and that they don’t duplicate content other users may have posted. To achieve this, add the following line to the file:

      ~/sharkapp/app/models/post.rb

      class Post < ApplicationRecord
        belongs_to :shark
        validates :body, presence: true, uniqueness: true
      end
      

      Save and close the file when you are finished editing.

      With this last change in place, you are ready to run your migrations and test the application.

      First, run your migrations:

      Next, start your server. If you’re working locally, you can do so by running:

      If you are working on a development server, run the following command instead:

      • rails s --binding=your_server_ip

      Navigate to your application’s root at http://localhost:3000 or http://your_server_ip:3000.

      The prerequisite Rails project tutorial walked you through adding and editing a Great White shark entry. If you have not added any further sharks, the application landing page will look like this:

      Shark App Landing Page

      Click on Show next to the Great White’s name. This will take you to the show view for this shark. You will see the name of the shark and its facts, and a Posts header with no content. Let’s add a post to populate this part of the form.

      Click on Add Post below the Posts header. This will bring you to the post index view, where you will have the chance to select New Post:

      Post Index View

      Thanks to the authentication mechanisms you put in place in Step 6 of How To Build a Ruby on Rails Application, you may be asked to authenticate with the username and password you created in that Step, depending on whether or not you have created a new session.

      Click on New Post, which will bring you to your post new template:

      New Post

      In the Body field, type, “These sharks are scary!”

      New Shark Post

      Click on Create Post. You will be redirected to the index view for all posts that belong to this shark:

      Post Success

      With our post resources working, we can now test our data validations to ensure that only desired data gets saved to the database.

      From the index view, click on New Post. In the Body field of the new form, try entering “These sharks are scary!” again:

      Repeat Shark Post

      Click on Create Post. You will see the following error:

      Unique Post Error

      Click on Back to return to the main posts page.

      To test our other validation, click on New Post again. Leave the post blank and click Create Post. You will see the following error:

      Blank Post Error

      With your nested resources and validations working properly, you now have a working Rails application that you can use as a starting point for further development.

      Conclusion

      With your Rails application in place, you can now work on things like styling and developing other front-end components. If you would like to learn more about routing and nested resources, the Rails documentation is a great place to start.

      To learn more about integrating front-end frameworks with your application, take a look at How To Set Up a Ruby on Rails Project with a React Frontend.



      Source link

      World Backup Day 2018: The Best Advice and Resources for Protecting Your Business’s Critical Data


      Celebrated since 2011 on March 31, World Backup Day is an annual clarion call to consumers and businesses alike to protect their most important information and data by making secure, accessible copies.

      The call to action has never been more important. The amount of data being produced and stored continues to exponentially grow in the digital era, and not coincidentally, cybersecurity threats are evolving in sophistication and volume.

      So even though backups shouldn’t be a focus just one day a year, especially for businesses, we fully endorse any trending Twitter hashtag that raises awareness.   

      Over the past few years, my colleagues and I at SingleHop’s ThinkIT blog have advocated numerous ways to take control. Below are few of my favorites pieces. If you haven’t read them yet, we hope you learn a thing or two. And if you’d rather just start backing up today, we’ve got a 30-day free trial of one of the best cloud backup services on the market ready and waiting.

      If you’re new to the world of cloud-based backup services, start with my overview of BaaS.

      In this blog, SingleHop’s Director of Solutions Architecture, Paul Painter, outlines the considerations for crafting a backup and retention policy based on business needs and criticality of data. A must read if you’re looking to kick your business continuity strategy up a notch.

      SingleHop’s very own Veeam Vanguard, Eugene K., shares his tips, tricks and go-to tools for calculating and planning storage requirements.

      While we’re already a quarter of the way through 2018, the Veeam-supported backup methods detailed in the this blog provide a great footing for any new World Backup Day resolutions.

      Finally, see how one of our clients transformed their business by implementing a Veeam Cloud Connect solution.

      Back Up to the Cloud with SingleHop & Veeam

      Off-site backups are critical. In just minutes, you could be backing up to the cloud with our free trial — no credit card required. Get Started.



      Source link

      The 70 Best Online Resources to Learn How to Code (Updated 2018)


      If you look back at tech movies of the past, some of them were really ahead of their time. Think back to 1995’s The Net, a film about computer analyst Angela Bennett (played by a young Sandra Bullock) who happens upon a government conspiracy — and dangerous hackers — while debugging a computer program. Not only did the film hit the nail on the head with how prevalent the internet is in our lives, but it also highlighted the power and pervasiveness of programming.

      Call it prophetic, but “hacking” skills — the good kind — are the common currency of the future. With an increasing interest in computer programming and the growth of tech-sector jobs, the time is now to learn a thing or two about 0s and 1s. It’s time to learn to code (no, not morse code).

      Maybe it was tech-of-the-future movies that got you interested in coding as a kid, or perhaps you’re developing a passion for learning mid-career. Whatever the reason, it’s time to go back to school — and with the right resources, you can learn a host of new language skills (no verb conjugating required).

      So what is coding? (If you’ve got some time, start here). Simply put, code is the set of instructions given to computers to perform specific functions. With lines of code, programmers develop the software that powers the devices you encounter every day — from your smartphone to your microwave. Yep, it does a lot.

      Programming is not just a way to build things; coding helps solve problems, aids people in need, and, as Steve Jobs admonished, it teaches you how to think. It’s a skill lauded by presidents, mayors, billionaires, even high fashion supermodels. There’s even a designated Computer Science Education Week. Mark your calendars!

      The good news is you don’t have to live in Silicon Valley or have expensive, high-tech gadgets to learn how to code. Self-taught programming is on the rise, and you can join the masses that are taking to the web to learn the next universal language.

      With the click of a mouse, you can develop a whole new repertoire of programming skills. And we’ve got all the resources to help you learn to code as you start the digital school year.

      Brrrrring! (Code) School is back in session.

      But First, Meet a Self-Taught Programmer

      Before I inundate you with stellar programming resources, allow me to introduce you to a real-life, self-taught coding graduate. Meet Ryan Hanna.

      Ryan Hanna

      Why him? Well, in 2015, more than half of mobile phone users had downloaded a health-related mobile app. And know who created one of the most successful ones? That’s right.

      Hanna began teaching himself to code in January of 2012 using Codeacademy, out of a desire to start creating his own projects.

      “I was tired of just consuming things that other people were building and wanted to try building something of my own,” he says.

      Utilizing lessons from Codeacademy, PhoneGap, and tutorials he found on blogs, he picked up programming skills and began working on his own creation — a new workout app called Sworkit.

      “I transitioned from an IT specialist to a full-time junior developer in the same company I worked for after one year of learning and had started building my own project in my free time,” Hanna says. “This project ended up replacing most of my resume and helped me get my first non-junior developer role where I worked for two years.

      “Along the way, I had met Benjamin Young of Nexercise at a conference, and we ended up deciding to work together on Sworkit full time. His and Greg Coleman’s company Nexercise bought Sworkit and hired me to continue working on it. We’ve since grown to an amazing team of seven and have one of the top workout apps on the market.”

      The growth of Sworkit proved to Hanna — and it should prove to you — that building something amazing is only a few steps away.

      “You can build anything you want,” Hanna says. “Starting with any idea or any design, you can just start building it without any limitations. That feels amazing to go from nothing to something.”

      And learning to code doesn’t have to be overwhelming. Start with baby steps, Hanna says.

      “Learn a broad spectrum of languages and topics at the start, but then pick something small to work on with what you have learned,” he says. “It will help you start something from scratch and get that feeling of adding one little piece at a time. You start to focus on figuring out how to complete each step in sequence and then you have something to show for it at the end as well.”

      A computer science degree isn’t required to get started with a shiny new set of coding skills. Many others have learned, and so can you.

      Here is a hefty list of 70 free or low-cost ways (and more) to get started.

      Self-Guided Tour: Our Complete List of 70 Coding Resources

      1. Games

      We know gaming isn’t time-wasting — rather, it’s an engaging way to learn and practice new concepts as you learn to code. Use these online activities to sharpen your skills.

      CodeFights

      Explore programming in your preferred coding language and on your own time. Whether you’ve got five minutes or five hours, Code Fights allows you to practice for job interviews, play arcade-style coding games, and compete in screen-to-screen challenges

      Cost: Free

      CodeAbbey

      A collection of beginner-to-advanced practice problems that allow you to earn certificates and hone your skills. Consider it a type of fun homework.

      Cost: Free

      Coderbyte

      Choose a coding language and solve challenges; accompanying solutions and tutorials help you cement crucial programming skills with step-by-step instructions

      Cost: Free

      FightCode

      Enter virtual duels by building your own robot using Javascript and challenging other users — programming video games, anyone?

      Cost: Free

      Reddit: Daily Programmer

      Utilize Reddit’s user-based forums to try challenges in a range of different levels and applications — everything from Scrabble-like tests to mazes.

      Cost: Free

      CodinGame

      Play virtual coding games (think: destroying enemy ships with code) that can teach you essential skills and can get you noticed by companies.

      Cost: Free

      CodeEval

      See how you stack up against other coders with a large library of dynamic coding challenges while building a profile and attracting the attention of programmer-seeking companies.

      Cost: Free

      HackerEarth

      Coding activities with purpose. Help solve real-world problems for businesses with innovative programming solutions while joining a community of coders and utilizing practice problems.

      Cost: Free

      HackerRank

      Unearth your inner coding competitor and solve challenges while interacting on a leading recruitment site for companies (meaning, it’s a resume builder!)

      Cost: Free

      Sphere Online Judge

      Become the Obi-Wan of programming by testing out problems and offering your own solutions, while participating in a unique coding community.

      Cost: Free

      Microsoft Imagine

      Enhance your development skills by taking Microsoft’s fun and creative coding projects for a spin.

      Cost: Free

      CodeWars

      A great resource to train yourself, collaborate with others, and create in a variety of programming languages.

      Cost: Free

      Exercism

      Practice problems (consider them mini-quests) for newbies and experts, tailored to your interests, whether you want to learn to code, increase fluency in your chosen language, or develop clean code. Just submit your solutions and get helpful feedback. Works through GitHub.

      Cost: Free

      2. Books

      No dull, dusty textbooks here — these programming tomes can provide you useful reading material.

      The Self-Taught Programmer

      The perfect manual for self-studiers, written by one of coding’s own amateur-turned-professional graduate.

      Cost: $4.99 Kindle Book

      Github Free E-Books

      A countless collection of ebooks on every possible programming topic, like how to learn Python or PHP.

      Cost: Many free — prices vary

      Reddit Free Programming Books

      Another exhaustive collection of online resources to help you increase your coding knowledge.

      Cost: Many free — prices vary

      3. Mentors/Meetups

      Want to meet with like-minded individuals? Find a mentor or coding event in your area.

      Reddit Programming Buddies

      Virtual classified ads for programmers; identify programming comrades that match your unique skills and interests and collaborate on personalized projects.

      Cost: Free

      Perunity

      A matching platform that connects users in a myriad of different fields; outfit a profile with what you offer and what you want to learn and begin sharing knowledge with other groups.

      Cost: Free

      Pair With Me

      Utilize the site’s Pair With Me button to encourage collaboration from your own website or contact form. Also, check out the provided collection of resources and guides for programmer pairing.

      Cost: Free

      CodeNewbies Twitter

      This social media handle hosts a live, weekly chat every Wednesday where users can ask questions and converse with other programmers — beginners and experts alike.

      Cost: Free

      Meetup

      A general connection platform that allows you to tailor specific meetup requests in your area. A good place to start? Tech Meetups.

      Cost: Prices vary

      Hackathons

      Not unlike a hip, adult slumber party; these all-night coding parties allow you to gather with like-minded learners and develop new skills as you tackle team programming projects.

      Cost: Prices vary

      Local Computer Science Classes

      For those looking to feel like a student again. Another Code.org resource that allows you to find computer science courses local to your area.

      Cost: Prices vary

      Girl Develop It

      A female-focused nonprofit that provides resources for computer science-interested women. Find your local chapter and attend programming events.

      Cost: Prices vary

      Did You Know? DreamHost has partnered with Girl Develop It to sponsor WordPress courses nationwide.

      Coder Match

      Link your GitHub account to find coding buddies that share similar programming goals and projects.

      Cost: Free

      Code Buddies

      A large community of programmers who connect via Slack and organized study (screen-sharing) hangouts. Make your hangouts as unique as your project.

      Cost: Free

      4. Videos

      Hunker down: it’s movie night. Time to break out the popcorn and watch as YouTubers — and others — share their knowledge. (Bonus: No Redbox fees).

      DevTips

      A Google employee shares weekly video lessons that address topics of web design and development.

      CSS-Tricks

      The YouTube channel of a matching site that addresses much more than just CSS.

      Derek Banas

      Your wish is Derek Banas command; the YouTuber makes video tutorials based on the requests and questions from viewers, so ask away! His tailored videos also include multi-weekly live streams. Along with an extensive collection of programming tutorials, he’s also got in-depth guides on how to create video games. Score!

      Coder’s Guide

      Helpful step-by-step web development tutorials covering everything from responsive web design to splash screens.

      The New Boston

      Covering all things computers, The New Boston offers detailed videos for every step of your programming journey — even for beginners.

      Programming Knowledge

      A great starting point for beginners; these easy-to-digest video help learners manage the ins-and-outs of different programming languages.

      Ted Talks

      A playlist of seven top-tier talks from Ted Talks’ best speakers, covering topics like teaching kids to code and improving government through programming.

      Command Line Power User

      A handy video series for web developers learning how to interact with computer programs.

      My Code School

      This educational channel has more than 330,000 subscribers for a reason: the folks behind it know their stuff. With tons of videos on a host of programming languages and live content, you can get a crash course on any programming subject you want to learn about.

      Looking for additional coding movie makers? Here are a few more you can check out.

      5. eCourses

      Choose from a handful of virtual courses or coding boot camps to learn new skills — at free or budget-friendly costs.

      GitHub

      A coder-must platform that helps programmers collaborate with each other as they save code online, view changes, and discuss issues.

      Cost: Paid (from $7 per month) and free plans available

      Bitbucket

      Another resource that makes coding a team effort; works in conjunction with Git to help programmers work jointly on projects.

      Cost: Paid (from $10 per month) and free plans available

      Open Culture

      A full list of all kinds of online computer courses from distinguished universities — available in various formats for easy accessibility.

      Cost: Free

      Code Avengers

      Whether you want to learn how to build websites, apps, or games, this resource has helpful lessons, quizzes, and project-based learning tools for creating and real-life problem solving, tailored to your own individual programming path. They even provide an educational environment for junior coders.

      Cost: $29 per month; $150 for six months

      Code.org

      Moana, Star Wars, and Minecraft — all subjects incorporated into one-hour tutorials provided by nonprofit Code.org. These easy-to-digest courses are accessible for learners of all levels and ages, and provide useful hands-on experience for future programming gurus

      Cost: Free

      Reddit

      Not just a programmer’s favorite; this Reddit page has a collective list of interactive coding tutorials gathered from around the web on various topics, from mobile iOs or Android development to info on different programming languages. (Plus, you can even watch people code!)

      Cost: Free

      GitHub Curated Programming Resources

      Another exhaustive list of coding resources, plus, a helpful introduction that guides beginners on where to start.

      Cost: Free

      Codeacademy

      Ryan Hanna’s alma mater is helping educate the world in programming; choose from a catalog of courses that meet your learning needs and get coding.

      Cost: Free

      David Walsh

      Web developer Walsh shares a host of programming tutorials in addition to sharing demos and info about coding conferences.

      Cost: Free

      Open Culture

      A collection of computer science courses and resources available right from your screen and in multiple formats.

      Cost: Free

      Treehouse

      A course-focused site that offers resources for learning, practicing, and earning badges that boost your skills. Students can earn anything from app-building to website-creation.

      Cost: Free 7-day trial, $25 (Basic Plan) or $49 (Pro Plan) a month after

      Coursera

      Take courses straight from actual universities in a variety of specializations. This site partners with top schools to offer education in programming, data science, business, and more.

      Cost: Prices vary

      EdX

      Students choose from an extensive collection of self-paced computer science courses fueled by university curriculum — it was founded by Harvard and MIT in 2012.

      Cost: Free, professional certificates at a cost

      Free Code Camp

      Complete challenges and building projects that can help you build skills, even acquire developer jobs. Plus, Free Code Camp tasks have practical applications, like aiding nonprofits with open source projects.

      Cost: Per its name, free

      General Assembly Dash

      Learn coding basics from your browser — the step-by-step guided fundamentals can aid you in building your next super-site.

      Cost: Free

      Udacity

      Earn a nanodegree — an online certification with provided course materials and instructor guidance — in one of seventeen available tech tracks. Learn in-demand job skills at your own pace.

      Cost: Prices vary (but plan for a cost of at least a few hundred every month).

      Solo Learn

      Learn to code on the go with online courses or a travel-friendly app. Topics feature tons of courses and quizzes, plus social learning components; there’s even a “Code Playground” for experimental development.

      Cost: Free

      Udemy

      Choose from more than 45,000 courses tailored to your own personal programming syllabus rated and reviewed by peers.

      Cost: Prices vary

      Lynda

      A learning platform filled with engaging courses taught by industry gurus.

      Cost: Free 30-day trial, prices vary after

      Self Taught Coders

      Email courses designed to help you launch a career in web development and propel your ideas into real-life web applications.

      Cost: Prices vary, some free

      MarkSheet

      An HTML and CSS tutorial that starts at the web’s bare bones and gets gradually more detailed as the course progresses — an easy-to-understand intro for beginners.

      Cost: Free

      Reddit: Learn Programming

      A smart guide with an abundance of helpful resources for every step of your self-taught programming journey.

      Cost: Free

      Haven’t found your perfect fit? Try this: a few more places to code for free.

      6. Podcasts

      Load up your device with audio coding lessons and listen on your commute or during your workout.

      Coding Blocks

      Shop talk about development best practices relevant to a number of different programming languages.

      Cost: Free

      Dev Radio

      A by developers, for developers podcast that shares up-and-coming programming news. Cost: Free

      Software Engineering Daily

      Featured interviews with experts that touch on tech topics like mobile app development and developer testing.

      Cost: Free

      Developer Tea

      A snackable-size podcast designed for busy schedules. Listen to quick bites on all kinds of developer-designed details.

      Cost: Free

      Programming Throwdown

      A perfect podcast if you want a little taste of everything; each show covers a different programming language so you can expand your coding knowledge with each episode.

      Cost: Free

      Coding Newbie

      This weekly podcast features stories and useful lessons from other individuals who are on their self-taught programming path.

      Cost: Free

      Learn to Code With Me

      Laurence Bradford’s weekly podcast helps self-taught coders transition to the tech field with useful real-world examples and tips on developing marketable skills and enhancing your resume.

      Cost: Free

      Need more earworms? Try additional podcasts here, including language- and task-specific channels.

      7. For Children

      Turns out, it’s never too soon to start introducing your tots to their first bytes.

      Computer Science for Babies

      A book series designed to help your little ones make connections to computer science principles during early development.

      Cost: Prices vary

      HTML for Babies

      A three-volume collection of board books that introduce your infants to computer science fundamentals. In conjunction with site Code Babies.

      Cost: Amazon, $1.73 each

      Treehouse: When Should Kids Learn to Code?

      Tips for helping kids to get a start in programming.

      Cost: Free

      Code.org Student

      A youthful resource for finding online courses or local classes. Includes games and activities.

      Cost: Free

      MoonHack

      A record-setting event for Code Club where kids ages 7-18 around the world join together to tackle projects — MoonHack’s or your own (moon-themed, of course). 2017’s MoonHack event brought together more than 28,000 youth.

      Cost: Free

      Code Your Own Games!

      Entice youth early to get involved in coding with this easy-to-follow (and super fun) visual guide that helps them learn to program their own games. Gaming + learning = win-win.

      Cost: Amazon, $16.16

      Got Questions?

      Our collection of resources provides a comprehensive list of places to initiate your self-taught programming journey, from beginning fundamentals to jump-starting your coding career. But along the way, you might hit a few roadblocks. Well, we’re here for you.

      Maybe you don’t know what programming language to start learning. Easy. Try an interactive quiz or infographic that guides your journey based on your individual goals and interests (like, creating a game, or developing an iOS or Android app).

      Struggling with framework questions, or need to fix a bug or in your code? Try utilizing Stack Overflow, a coder’s knowledge-sharing community. Want to automate tedious tasks while using Microsoft devices? Do it with Windows PowerShell. Trying to learn how to master an object-oriented programming language? Visualize with the Understand tool.

      Or perhaps you’re looking for useful apps or a development environment to practice in? We’ve got you covered. Try some note-taking apps that help while you code and useful coding playgrounds like Code Pen, JSFiddle, or Limnor Studio (visual programming) to get your feet wet.

      Any more questions? Let us know.

      Take Notes

      Ready for your homework? Time to get coding.

      Pick a course, a video, a podcast, or a coding game. Start there and start small. With our complete guide to coding resources, you have everything you need to start building your own projects and becoming fluent in your new language.

      Fill Us In

      Are you a self-taught programmer? How did you learn to code? What advice would you give to other wannabe coders? Share your story — and your advice — with us in the DreamHost Community!





      Source link