I have been working on this for many hours now and have started over several times (from a backup point) trying to figure out the problem.
I am trying to add comments to posts. Comments work fine, it's getting the username and avatar to show up that's not working. Here is what I did step by step.
1) rails g model Comment body:text user:references post:references
2) I verified that the model was correct
class Comment < ApplicationRecord
belongs_to :user
belongs_to :post
end
3) rake db:migrate
4) Added has_many :comments, dependent: :destroy
to both user.rb and post.rb
5) Added resources :comments
to my routes.
resources :posts do
resources :comments
member do
post '/like' => 'posts#like'
end
end
6) Generated comments controller rails g controller comments
7) Altered the comments the comments controller:
class CommentsController < ApplicationController
def create
@post = Post.find(params[:post_id])
@comment = @post.comments.create(params[:comment].permit(:body))
@comment.user = current_user
if @comment.save
redirect_to post_path(@post)
else
# something else
end
end
end
8) Created two partials "_comment.html.erb" and "_form.html.erb" in comments' view folder.
"_comment.html.erb"
<h2><%= @comment.user.name %></h2>
<p><%= comment.body %></p>
"_form.html.erb"
<%= form_for([@post, @post.comments.build]) do |f| %>
<p>
<%= f.text_field :body %>
</p>
<p>
<%= f.submit %>
</p>
<% end %>
9) Added comments to posts' show page
<h4><%= @post.comments.count %> comments</h4>
<%= render @post.comments %>
<h2>Add a comment</h2>
<%= render "comments/form"%>
10) Restarted server
11) Tried to create a comment and got the following error:
NoMethodError in Posts#show
undefined method `user' for nil:NilClass
<h2><%= @comment.user.name %></h2> #THIS LINE IS THE ERROR
Aucun commentaire:
Enregistrer un commentaire