[英]How to allow users delete their own comments and not others
在我的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>
我看不到用戶和評論之間沒有任何聯系,在這里我沒有正確的方法。有人可以指導我這樣做,這樣我就可以不使用任何寶石。
您似乎在Comment
和User
之間沒有任何關系。 假設您要存儲每個注釋的user_id
,則在Comment
類中將需要類似以下內容:
belongs_to :user
然后在您的CommentsController
destroy
方法應如下所示:
def destroy
# Only the comments posted by that user will be returned
@comment = @user.comments.find(params[:id])
@comment.destroy
end
如果沒有,在注釋表中添加use_id
add_column :comments, :user_id, :integer
在您的視圖文件中放置以下條件。 刪除鏈接僅對添加評論的用戶可見。
<% if user_signed_in? && current_user.id == comment.user_id %>
<p><%= link_to 'Delete', [comment.tale, comment], method: :delete, data:
{ confirm: 'Are you sure?' } %></p>
<% end %>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.