Search code examples
ruby-on-rails-4parameterscommentsattr-accessible

Commenting model not saving and displaying :body section of comments


I'm new to rails and am having challenges adding a commenting system to my listings model. Effectively I have listings that are created by users, and I want the ability to allow other users to make comments on these listings.

What I have so far:

A listing model that includes:

has_many :comments

a comment model that includes:

belongs_to :listing

a comments controller:

class CommentsController < ApplicationController

def create

  @listing = Listing.find(params[:listing_id])

  @comment = @listing.comments.build(params[:body]) # ***I suspected that I needed to pass :comment as the params, but this throws an error.  I can only get it to pass with :body ***

 respond_to do |format|

  if @comment.save

    format.html { redirect_to @listing, notice: "Comment was successfully created" }

    format.json { render json: @listing, status: :created, location: @comment }

  else

    format.html { render action: "new" }

    format.json { render json: @comment.errors, status: :unprocessable_entity }

   end
  end
 end
end


def comment_params
   params.require(:comment).permit(:body, :listing_id)
end

and finally a listing view that includes the following code to collect and display comments:

       <div class="form-group">
          <%= form_for [@listing, Comment.new] do |f| %>
          <%= f.label :comments %>
          <%= f.text_area :body, :placeholder => "Tell us what you think", class: "form-control", :rows => "3" %>
          <p><%= f.submit "Add comment", class: "btn btn-primary" %></p>
          <% end %>
        </div>

      <%= simple_form_for [@listing, Comment.new] do |f| %>
      <p>
        <%= f.input :body, :label => "New comment", as: :text, input_html: { rows: "3" } %>
      </p>
      <p><%= f.submit "Add comment", class: "btn btn-primary" %></p>
      <% end %>

The comment box is displaying correctly in the view, and I'm able to submit comments, however it appears that the :body isn't being saved, and therefore the "submitted x minutes ago" is the only thing that's showing up in my comments section.

Any ideas on what I could be doing incorrectly? I suspect it's a params issue, but haven't been able to work it out.

Thanks!


Solution

  • Since you are using the strong_parameters paradigm in Rails 4, I think you should change the comment creation line to this:

     @comment = @listing.comments.build(comment_params)
    

    And I'd change the listing finding line to this:

     @listing = Listing.find(params.permit(:listing_id))
    

    It should work fine, as long as you correctly whitelist all required params in the comment_params method.