Rails 4,acts_as_commentable,删除按钮/链接

[英]Rails 4, acts_as_commentable, delete button / link


I have a User model which is commentable:

我有一个可评论的用户模型:

class User < ActiveRecord::Base
  acts_as_commentable

In the Users controller I am grabbing the comments like this:

在Users控制器中,我抓住这样的评论:

@comments = @user.comments.recent.page(params[:notifications]).per(10)

And in the Users show view there is a partial which renders the comments:

在Users show视图中,有一个部分呈现注释:

<% @comments.each do |comment| %>
  <p><%= time_ago_in_words(comment.created_at) %> ago</p>
  <h4><%= comment.comment %></h4>
<% end %>

I'm having trouble adding a link or button in the partial to lets Users delete (preferably via an AJAX call) individual comments. I know this is basic Rails but I am completely lost here.

我在部分中添加链接或按钮时遇到问题,以便用户删除(最好通过AJAX调用)个人注释。我知道这是基本的Rails,但我完全迷失在这里。

Further info:

class Comment < ActiveRecord::Base
  include ActsAsCommentable::Comment
  belongs_to :commentable, :polymorphic => true
  default_scope -> { order('created_at ASC') }
  belongs_to :user
end

I'd really appreciate a concise and complete answer to this.

我真的很感激这个简洁而完整的答案。

I didn't include routes.rb because currently Comments are only created in callbacks to other User actions. There is therefore no info concerning Comments in routes.rb

我没有包含routes.rb,因为目前只在回调到其他用户操作时创建了注释。因此,在routes.rb中没有关于评论的信息

1 个解决方案

#1


0  

Ok as usual the solution was simple:

好像往常一样,解决方案很简单:

routes.rb:

resources :comments, only: :destroy

UsersController:

def show
  @comments = @user.comments.recent.page(params[:notifications]).per(10)
end

views/users/_comments.html.erb:

<% @comments.each do |comment| %>
  <span id="<%= comment.id %>">
    <p><%= time_ago_in_words(comment.created_at) %> ago</p>
    <h4>
      <%= comment.comment %>
      <%= link_to comment, method: :delete, remote: true %>
    </h4>
  </span>
<% end %>

CommentsController:

def destroy
  @user = current_user
  @comment = Comment.destroy(params[:id])
  respond_to do |format|
    format.html { redirect_to user_path(@user) }
    format.xml  { head :ok }
    format.js
  end
end

views/comments/destroy.js.erb:

$('#<%= @comment.id %>').remove();

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2014/03/31/a82c44bd80ef44819abc6922b63d1ad2.html



 
粤ICP备14056181号  © 2014-2021 ITdaan.com