简体   繁体   中英

Allowing users to delete their own comments in rails 3

For each post, there are postcomments.

Here's what the model for the Postcomment looks like:

class Postcomment < ActiveRecord::Base
  attr_accessible :comment_content

  belongs_to :user
  belongs_to :post
end

and the Post model

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

I would like to allow users to delete their own postcomments. This is what I already have in the view

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

How should this code below be changed to allow users to delete comments?

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

current_user methods in Sessions helper

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

Here's the Postcomments table

 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

Perhaps...

if current_user == postcomment.user

If current_user returns a user instance anyways...

It might be better if you just compared the user id's. This is also easier to debug.

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

也许是这样的:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM