Seuls les utilisateurs connectés peuvent publier et commenter. Seul le créateur peut supprimer le commentaire.
post.rb
class Post < ApplicationRecord
belongs_to :user
has_many :comments
end
comment.rb
class Comment < ApplicationRecord
belongs_to :post
end
Vous pouvez utiliser post_id et id (de l'utilisateur) dans les paramètres.
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
L'identifiant de l'utilisateur créé par <% = f.hidden_field: user_id, value: current_user.id%>
est passé.
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