允许用户在rails 3中删除自己的注释

时间:2013-04-16 16:12:44

标签: ruby-on-rails ruby

对于每篇帖子,都有后期评论。

以下是Postcomment的模型:

class Postcomment < ActiveRecord::Base
  attr_accessible :comment_content

  belongs_to :user
  belongs_to :post
end

和Post模型

class Post < ActiveRecord::Base
  attr_accessible :content, :image, :comment_content
  belongs_to :user
  has_many :postcomments, dependent: :destroy
end

我想允许用户删除自己的帖子。这就是我在视图中已有的内容

_postcomment.html.erb

<% if post.postcomments.exists? %>
  <% post.postcomments.each do |postcomment| %>
    <%= link_to postcomment.user.name, postcomment.user %>
    <span class="content2"><%= postcomment.postcomment_content %></span>
  <% end %>
<% end %>

如何更改以下代码以允许用户删除评论?

 <% if current_user?(postcomment.user) %>
    <%= link_to "delete", postcomment.content, method: :delete,
                                             confirm: "You sure?",
                                             title: postcomment.content %>
 <% end %>
Sessions helper中的

current_user个方法

def current_user=(user)
    @current_user = user
  end

  def current_user
    @current_user ||= User.find_by_remember_token(cookies[:remember_token])
  end

  def current_user?(user)
    user == current_user
  end

这是Postcomments表

 create_table "postcomments", :force => true do |t|
    t.text      "content"
    t.integer   "user_id"
    t.integer   "post_id"
    t.timestamp "created_at",      :null => false
    t.timestamp "updated_at",      :null => false
    t.text      "comment_content"
  end

3 个答案:

答案 0 :(得分:1)

...也许

if current_user == postcomment.user

如果current_user仍然返回用户实例......

答案 1 :(得分:1)

如果您只是比较用户ID,可能会更好。这也更容易调试。

def current_user?(user)
  user.id == current_user.id
end

答案 2 :(得分:0)

可能是这样的:

<%= link_to("delete", postcomment.content, :method => :delete, :confirm => "You sure?", :title => postcomment.content) if postcomment.user == current_user %>