Search code examples
ruby-on-railsrenderpartial

Creating a partial rails for comments


My topic is very similar to this question, except that my comments are shown inside of a bootstrap modal. I need to create a comments partial so that I can use respond_to |format| do format.js to render the partial and update the comments in the modal.

Question #1. How do I create a comments partial? Here is the code:

CommentsController

def create
    @photo = Photo.find(params[:photo_id])
    @comment = @photo.comments.build(comment_params)
    @comment.save
    respond_to do |format|
      format.html { redirect_to :back }
      format.js 
    end 
end 

UsersController

def show
  @user = User.find(params[:id])
  @photos = @user.photos.order('created_at desc').paginate(page: params[:page], per_page: 12)
end

Users/show.html.erb   

<% @photos.in_groups_of(3, false).each do |group| %>
    <div class="row instagram">
      <% group.each do |photo| %>
        <a data-toggle="modal" href=<%="#"+"#{photo.id}"%>>
          <%= image_tag(photo.picture.ad.url, class: "img-responsive")%>
        </a>  
        <div class="modal" id=<%="#{photo.id}"%> tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel">
        .
        .      
         <div class="col-sm-4">
           <div class="instacomments">
             <% photo.comments.each do |comment| %>
               <p class="commentblock">
                  <%= link_to comment.user.name, user_path(comment.user_id)%><span> </span><%= comment.content %> 
               </p>
             <% end %>
           </div>
         </div>          

Solution

  • In your show.html.erb:

    <%= render partial: "comments/comment", collection: photo.comments, as: :comment %>
    

    Note the the as: :comment key is what sets the name of the local variable for each collection item in your view.

    So now you can reference the comment variable in comments/_comment.html.erb:

    <p class="commentblock">
       <%= link_to comment.user.name, user_path(comment.user_id)%>
       <span> </span> <!-- Not sure why you have an empty <span> here -->
       <%= comment.content %> 
    </p>