When I tried to delete comments, I have an error that "undefined method `destroy' for nil:NilClass"
When I add comment to different microposts;all comments micropost_id is same and display all comments below all microposts.
I will be grateful if someone help me add comments to microposts. I've tried for two weeks this issue and I have NOTHING :(
create_comments.rb
def change
create_table :comments do |t|
t.string :commenter_id
t.text :body
t.references :micropost, index: true, foreign_key: true
t.timestamps null: false
end
comments_controller.rb
def create
micropost = Micropost.find_by(params[:id])
@comment = micropost.comments.build(comment_params)
@comment.commenter_id = current_user.id
@comment.save
redirect_to root_url
end
def destroy
@comment.destroy
flash[:success] = "Comment deleted"
redirect_to request.referrer || root_url
end
_comment.html.erb
<% @comment.each do |comment| %>
<p><%= comment.body %></p>
<span class="timestamp">
Posted <%= time_ago_in_words(comment.created_at) %> ago.
<%= link_to "delete", comment, method: :delete %>
</span>
<%end%>
_comment_form.html.erb
<%= form_for(Comment.new) do |f| %>
<p>
<%= f.text_area :body, :placeholder => "Leave a comment" %>
</p>
<p>
<%= f.submit %>
</p>
<% end %>
routes.rb
resources :microposts
resources :comments
_micropost.html.erb
<li id="micropost-<%= micropost.id %>">
<%= link_to micropost.user.name, micropost.user %>
<%= micropost.content %>
<div id="comments">
<%= render "comments/comment" %>
</div>
<%= render 'shared/comment_form' %>
</li>
microposts_controller.html.erb
def show
@micropost = Micropost.find(params[:id])
@comment = @micropost.comments(params[:id])
end
static_pages_controller.html.erb
def home
if logged_in?
@micropost = current_user.microposts.build
@feed_items = current_user.feed.paginate(page: params[:page])
@comment = Comment.all
end
end
Aucun commentaire:
Enregistrer un commentaire