Displaying the content


In this section we will learn how to use Rails to display the content in our system.

Creating a new migration

If we want to have our own posts in the application, we need a database table where we can store and keep track of them.

As you remember, in order to make any changes in databases rails uses migrations. We will now generate a migration that will create a posts table.

We start with storing the images URLs, post titles and descriptions in our database. Right now, if the users want to post something, they have to upload the image to a separate service like imgur.com or unsplash.com, then copy and paste the image URL. Our post will be defined by the link to the image.

In order to obtain the links to images you find somewhere on the internet, right click on the image, and select for Firefox Copy Image Location, or for Google Chrome Copy Image URL.

The posts table will contain the list of posts, each post having an image link, description and title. And since title and image link are a string of characters, we will define the them as strings, while description will be a text field meaning that it will also be a string of character but of bigger size.

To generate the migration, we use the following command in the terminal:

$ rails generate migration create_posts title:string description:text image_link:string

This migration will create a table to store posts.

After the migration is created, we migrate the database using the rake tool:

$ rails db:migrate

Creating a model

Having created the database table, we still have to create a model the database will use.

Make a new file in app/models and name it post.rb. Inside the new file type and save the following lines:

class Post < ActiveRecord::Base 
end

Using ERB to visualize posts

In the previous section, we created the views/posts/index.html.erb page containing a list of posts we had written by hand.

Let's change the file and make it display the posts we have in the database. To do this, we need to go through each post and display the image link.

Let's replace the previous code with the following:

<h1>Posts</h1>
<ul>
  <% Post.all.each do |post| %>
    <li>
      <p><%= post.title  %></p> 
      <p><%= post.description %></p>
      <p><%= image_tag(post.image_link )  %></p>
    </li>
  <% end %>
</ul>

This will display, for each post post a list item containing the word Post: and the image_link, title and description from this post. The <p></p> tags are HTML paragraphs, we added them to have a little more white space around the content.

We save the file, go to localhost:3000/posts. And see nothing. Which is expected, because we do not have, in fact, any post stored in the database.

To display content, we should first have it. So let's make it possible adding new posts.

results matching ""

    No results matching ""