显示评论创建者的删除链接

时间:2012-12-17 23:58:09

标签: ruby-on-rails

我的应用程序正在运行,以便用户只能删除自己的评论,但现在我尝试添加链接到网站,但我只希望评论的创建者能够看到链接。

我试过

<% if current_user %>

但是当我这样做时,它会显示所有评论,而不仅仅是用户。我能做到

<% if current_user.admin %> 

并且仅限制管理员才能看到删除链接。我也试过了

 <% if @comment.user_id == current_user.id %>

也是如此。我该怎么做才能让评论创建者只看到评论?

继承人的观点

_comments.html.erb

  <div class="container">
  <% @comments.each do |comment| %>
  <div class="comment">
<div class="gravatar_border">
  <%= gravatar_for comment.user, size: '49' %>
</div>

<div class="user_info_comments">
  <b><%= comment.user.name %></b>
  <%= comment.created_at.strftime("%b. %d  %Y") %>
</div>

<div class="user_comments">
  <%= simple_format comment.content %> 
  <%= pluralize comment.reputation_value_for(:votes).to_i, "vote" %>
  <%= link_to "", vote_comment_path(comment, type: 'up'), method: "post", class: ' icon-thumbs-up' %>
  <%= link_to "", vote_comment_path(comment, type: 'down'), method: "post", class: ' icon-thumbs-down' %>
  <% if @comment.user_id == current_user.id %>
  <%= link_to 'delete', comment, method: :delete, confirm: 'you sure?' %>
  <% end %>
   </div>
  </div>
 <% end %>
 <br />
</div>

继承我的控制器

comments_controller.rb

  def destroy
      @comment = Comment.find(params[:id])
      if @comment.user_id == current_user.id
        @comment.destroy
        flash[:notice] = "comment deleted!"
      else
        flash[:error] = "not allowed"
      end
   redirect_to :back
 end 

表示网站http://www.batman-fansite.com

的链接

2 个答案:

答案 0 :(得分:2)

在您的视图中将@comment更改为comment

<% if comment.user_id == current_user.id %>

@comment已在您的destroy操作中定义,但是当您在视图中设置此类阻止时

<% @comments.each do |comment| %>

@comment没有价值,只有comment

答案 1 :(得分:1)

<% if comment.user_id == current_user.id %>

并且应该工作)