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 = @link.comments.new(comments_params)
@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)
end

#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
</h3>

#getting the count of comments

<div id=”comments”>
<%= render :partial => @link.comments %> #rendering another html partial for comments
</div>
<%= simple_form_for [@link, Comment.new] do |f| %> #lets us create a comment
<div class=”field”>
<%= f.text_area :body, class: “form-control” %>
</div>
<br>
<%= 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 <%= comment.user.email %></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 %>
</div>
</div>
<% end %>

 

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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