Question

So I got into trouble with ruby on rails while creating comments. I don't get any errors, but my comments doesn't show up either.What am i doing wrong ? I am trying to debug it for past 2 hours :X

my show.html.erb

<h2>Comments</h2>

   <%=  @article.comments.each do |comment| %>
      <strong><%= comment.body %></strong> <br />
      <hr />
<% end %>

<%= form_tag :action => "comment", :id => @article %>
   <%= text_area "comment", "body" %><br />
   <%= submit_tag "Comment" %>
</form>

my articles controller:

 def comment
   Article.find(params[:id]).comments.create(params[comment_params])
   flash[:notice] = "Added your comment"
   redirect_to :action => "show", :id => params[:id]
end

and my routes

 resources :articles do
  post 'comment', on: :member
end

Please tell me, why it doesn't save my text ? When i create a comment, i check it, and see:

#<Comment id: 21, email: nil, body: nil, created_at: "2014-04-27 13:27:40", updated_at: "2014-04-27 13:27:40", user_id: nil, article_id: 3>]

Don't mind the user_id: nil, i created it accidentally, and intend to remove it ^^ Once we fix this problem ^^

Was it helpful?

Solution

Your issue is how you are attempting to use strong parameters.

You are currently doing

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

params[comment_params]

What you want to do is something like

def comment_params
  require(:comment).permit(:body)
end

params.comment_params

OTHER TIPS

The problem is in this line

Article.find(params[:id]).comments.create(params[comment_params])

It should be like this

Article.find(params[:id]).comments.create(comment_params)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top