0

对于每个帖子,都有帖子评论。

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

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
4

3 回答 3

1

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

def current_user?(user)
  user.id == current_user.id
end
于 2013-04-16T20:55:41.140 回答
1

也许...

如果 current_user == postcomment.user

如果 current_user 无论如何都返回一个用户实例......

于 2013-04-16T16:40:11.433 回答
0

也许是这样的:

<%= link_to("delete", postcomment.content, :method => :delete, :confirm => "You sure?", :title => postcomment.content) if postcomment.user == current_user %>
于 2013-04-16T21:02:41.540 回答