Only logged-in users can post and comment. Only the creator can delete the comment.
post.rb
class Post < ApplicationRecord
belongs_to :user
has_many :comments
end
comment.rb
class Comment < ApplicationRecord
belongs_to :post
end
You can use post_id and id (of user) in the parameters.
routes.rb
Rails.application.routes.draw do
devise_for :users
resources :posts do
resources :comments, only: [:create, :destroy]
end
root "posts#index"
end
post_comments POST /posts/:post_id/comments(.:format) comments#create
post_comment DELETE /posts/:post_id/comments/:id(.:format) comments#destroy
comments_controller.rb
def create
@post = Post.find(params[:post_id])
@post.comments.create(comment_params)
redirect_to post_path(@post)
end
def destroy
@post = Post.find(params[:post_id])
@comment = @post.comments.find(params[:id])
@comment.destroy
redirect_to post_path(@post)
end
private
def comment_params
params.require(:comment).permit(:body, :user_id)
end
The id of the user created by <% = f.hidden_field: user_id, value: current_user.id%>
is passed.
show.html.erb
<p>
<strong>Post:</strong>
<%= @post.post %>
</p>
<% if @post.user_id == current_user.id %>
<%= link_to 'Edit', edit_post_path(@post) %> |
<% end %>
<%= link_to 'Back', posts_path %>
<h3>Comments</h3>
<% @post.comments.each do |comment|%>
<ul>
<li><%= comment.body %>
<span>
<% if comment.user_id == current_user.id %>
<%= link_to '[X]', post_comment_path(@post, comment), method: :delete %>
<% end %>
</span>
</li>
</ul>
<% end %>
<%= form_for [@post, @post.comments.build] do |f| %>
<div class="field">
<%= f.text_field :body, autofocus: true, autocomplete: "body" %>
</div>
<div class="field">
<%= f.hidden_field :user_id, value: current_user.id %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
Recommended Posts