在我的Rails应用中,我有一个评论模型,一个设计用户模型和一个故事模型。对于每个故事帖子,我都有登录用户发表的评论。这里的问题是其他所有登录用户都可以删除其他用户的评论。我想要一个功能,只有创建评论的用户才能删除它。如何让用户删除自己的评论而不是其他人
我user.rb在这里
class User < ActiveRecord::Base
has_one :profile, dependent: :destroy
has_many :tales, dependent: :destroy
end
我comment.rb在这里
class Comment < ActiveRecord::Base
belongs_to :tale
end
我tale.rb在这里
class Tale < ActiveRecord::Base
belongs_to :user
has_many :comments, dependent: :destroy
belongs_to :category
end
我的routes.rb如下:
Rails.application.routes.draw do
get 'tales/index'
devise_for :users, controllers: { registrations: "registrations" }
resources :profiles
resources :tales do
resources :comments
end
resources :categories
authenticated :user do
root "tales#index"
end
unauthenticated :user do
get "/" => "tales#index"
end
end
我的评论控制器是在这里:
class CommentsController < ApplicationController
before_action :authenticate_user!
def create
@tale = Tale.find(params[:tale_id])
@comment = @tale.comments.create(comment_params)
redirect_to tale_path(@tale)
end
def destroy
@tale = Tale.find(params[:tale_id])
@comment = @tale.comments.find(params[:id])
@comment.destroy
end
private
def comment_params
params.require(:comment).permit(:name, :body, :tale_id)
end
end
从我的故事/显示页面中加入评论摘录是在这里:
<div id="comments">
<h2><%= @tale.comments.count %> Comments</h2>
<%= render @tale.comments %>
<h3>Add a comment:</h3>
<%= render "comments/form" %>
</div>
</div>
我_comment.html.erb在这里
<div class="comment clearfix">
<div class="comment_content">
<p class="comment_name"><strong><%= comment.name %></strong></p>
<p class="comment_body"><%= comment.body %></p>
<p class="comment_time"><%= time_ago_in_words(comment.created_at) %>
Ago</p>
</div>
<% if user_signed_in? %>
<p><%= link_to 'Delete', [comment.tale, comment], method: :delete, data:
{ confirm: 'Are you sure?' } %></p>
<% end %>
</div>
我看不到用户和评论之间的联系,我没有正确的方式来做到这一点。可以有人引导我通过这样做,我可以做到这一点,而无需使用任何宝石。
您必须在评论表中添加user_id,然后才能完成相同的操作。 – LHH