2016-03-16 43 views
0

在我的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> 

我看不到用户和评论之间的联系,我没有正确的方式来做到这一点。可以有人引导我通过这样做,我可以做到这一点,而无需使用任何宝石。

+0

您必须在评论表中添加user_id,然后才能完成相同的操作。 – LHH

回答

1

您看起来没有CommentUser之间的关系。您需要像这样在你Comment类假设你存储user_id为每个评论:

belongs_to :user 

然后在你的CommentsControllerdestroy方法应该是这样的:

def destroy 
    # Only the comments posted by that user will be returned 
    @comment = @user.comments.find(params[:id]) 
    @comment.destroy 
    end 
+0

他在评论表中没有user_id。检查他的问题 – LHH

+0

我尝试过...将user_id添加到注释和上面的代码中。但是当我检查注释时,它不会选择用户ID @Tom Rossi –

+0

@MaheshMesta是否在给注释分配user_id时产生的? –

0

use_id评论表如果没有

add_column :comments, :user_id, :integer 

在您的视图文件中放置以下con dition。删除链接仅对添加评论的用户可见。

<% 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 %> 
+0

添加user_id以评论模型和上面的代码。在评论创建@LHH后,它不会选择注释user_id并显示为nill –

相关问题