GVS GVS - 4 months ago 9
Ruby Question

Ruby on Rails: Having trouble adding a description to blog

I am new to rails. And I'm following a tutorial on how to create a blog in rails.

In the tutorial, the teacher creates a post with a title and body. All posts are displayed on the index page. Only the title of posts and the date it was published are displayed on the index page. If you click a post, you will be taken to, for example, "localhost:3000/posts/1" where you can see the title, date, body and comments for that post.

What I'm trying to do

Instead of just displaying the title and date of each post on the index page, I want to display a title, date and a short description of each post.

What I did

The ORIGINAL

new.html.erb
is a page to create new posts, and part of it looked like this:

<%= form_for :post, url: posts_path do |f| %>
<%= f.text_field :title %>
<%= f.text_area :body %>
<% end %>


So I added:





My ORIGINAL posts model:

class CreatePosts < ActiveRecord::Migration
def change
create_table :posts do |t|
t.string :title
t.text :body

t.timestamps
end
end
end


So, I added:


t.string :description


That did not work. So I tried to do this in a terminal

$ rails g model Post title:string description:string body:text --force


That was even worse. Overall, I ended up with so many errors I just restarted the tutorial.

So, my question is: "How can I add a description to my posts?"

Answer

Please follow below steps:

Step 1:Migration to add a new field using rails generator.

rails g migration add_description_to_posts

Step 2: In generated migration file:

class AddDescriptionsToPosts < ActiveRecord::Migration
  def change
    add_column :posts, :description, :string        
  end
end

Step 3: Migrate datbase

rake db:migrate

Step 4:Change in view.

<%= form_for :post, url: posts_path do |f| %>
 <%= f.text_field :title %>
 <%= f.text_area :body %>
 <%= f.text_area :description %>
<% end %>

Step 5: In PostController.rb, add description in white list parameters:

def post_params
  params.require(:post).permit(:title, :body, :description)
end

Let me know if you face any difficulty.