Building a Reddit Clone Pt.5

To add the functionality of adding comments, we’re going to run another scaffold:

rails g scaffold Comment link_id:integer:index body:text user:references –skip-stylesheets

next we want to add a gem called ‘simple form’ to our gemfile and bundle install it.

To make an association between links and comments we need to make sure that comment

belongs_to :link

and a link,

has_many :comments

adding comments as a resource into our routes.rb file makes sure we can create,delete,edit and update them:

resources :comments

Next we want to edit our comments_controller and redefine the create method with:

def create
@link = Link.find(params[:link_id])
@comment =
@comment.user = current_user

#we are looking up our link by a link_id parameter, then passing new comments with  parameters that are defined in a private segment of our controller:

def comment_params
params.require(:comment).permit(:link_id, :body, :user_id)

#and at last, assigning comments to a user.


Giving users the ability to comment is what we are doing in the show page, adding a form:

<h3 class=”comments_title”>
<%= @link.comments.count %> Comments

#getting the count of comments

<div id=”comments”>
<%= render :partial => @link.comments %> #rendering another html partial for comments
<%= simple_form_for [@link,] do |f| %> #lets us create a comment
<div class=”field”>
<%= f.text_area :body, class: “form-control” %>
<%= f.submit “Add Comment”, class: “btn btn-primary” %>
<% end %>

adding the comment partial:

<%= div_for(comment) do %>
<div class=”comments_wrapper clearfix”>
<div class=”pull-left”>
<p class=”lead”><%= comment.body %></p> #showing comment body
<p><small>Submitted <strong><%= time_ago_in_words(comment.created_at) %> ago</strong> by <%= %></small></p>
</div> #submitted x time ago by x user

<div class=”btn-group pull-right”>
<% if comment.user == current_user -%> #if the user is the current user, give him the ability to destroy it

<%= link_to ‘Destroy’, comment, method: :delete, data: { confirm: ‘Are you sure?’ }, class: “btn btn-sm btn-default” %>
<% end %>
<% end %>



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s