On a user's profile page, a user can create posts. I've recently added a delete link for users to delete their posts. The problem however, each individual post is showing all delete links for all posts.
Example: So if Jimmy has 3 posts, each post will have 3 delete links
The delete links work fine, I just need the right one to be displayed to it's individual post.
Here's my code:
posts_controller.rb
class PostsController < ApplicationController
def index
@posts = Post.allow
end
def new
@post = Post.new
end
def create
@post = Post.new(post_params)
@post.user_id = current_user.id # assign the post to the user who created it.
respond_to do |f|
if (@post.save)
f.html { redirect_to "", notice: "Post created!" }
else
f.html { redirect_to "", notice: "Error: Post Not Saved." }
end
end
end
def destroy # users can delete their own posts
@post = Post.find(params[:id])
if current_user == @post.user
@post.destroy
end
redirect_to root_path
end
private
def post_params # allows certain data to be passed via form.
params.require(:post).permit(:user_id, :content)
end
end
profile.html.erb
<div class="row">
<div class="col-xs-12">
<div class="jumbotron">
<%= @username %>
</div>
</div>
</div>
<!-- row 2 -->
<div class="row">
<div class="col-xs-3">
<div class="panel panel-default">
<div class="panel-body">
avatar
</div>
</div>
</div>
<div class="col-xs-6">
<%= render '/components/post_form' %><br>
<% for @p in @posts %>
<div class="panel panel-default post-panel">
<div class="panel-body row">
<div class="col-sm-1">
<img src="/avatar.png" class="post-avatar" height="50px" width="50px"></img>
</div>
<div class="col-sm-11">
<p class="post-title"><span class="post-owner"><a href="/user/<%= User.find(@p.user_id).username %>"><%= User.find(@p.user_id).name %></a></span> <span class="post-creation">- <%= @p.created_at.to_formatted_s(:short) %></span></p>
<p class="post-content"><%= @p.content %></p>
</div>
<div class="col-sm-12">
<p class="post-links">
<span class="glyphicon glyphicon-comment g-links" aria-hidden="true"></span>
<span class="glyphicon glyphicon-retweet g-links" aria-hidden="true"></span>
<span class="glyphicon glyphicon-heart g-links" aria-hidden="true"></span>
<span class="glyphicon glyphicon-option-horizontal g-links" aria-hidden="true"></span>
<% if user_signed_in? %>
<% @posts.each do |post| %>
<%= link_to 'Delete', post, method: :delete, data: { confirm: 'Are you sure?' } %>
<% end %>
<% end %>
</p>
</div>
</div>
</div>
<% end %>
</div>
<div class="col-xs-3">
<div class="panel panel-default">
<div class="panel-body">
<p>who to follow</p>
</div>
</div>
<div class="panel panel-default">
<div class="panel-body">
<p>trends</p>
</div>
</div>
</div>
</div>
What should I do in order to fix this problem? Thanks in advance!
The problem is in
profile.html.erb
:Remove the
@posts.each
loop, and replace it with: