gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 05:50:35 26 4
gpt4 key购买 nike

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

class User < ActiveRecord::Base
acts_as_commentable

在用户 Controller 中,我正在抓取这样的评论:

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

在“用户显示” View 中,有一个部分呈现评论:

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

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

更多信息:

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

我真的很感谢对此问题的简洁而完整的回答。

我没有包含routes.rb,因为目前评论仅在对其他用户操作的回调中创建。因此,routes.rb 中没有有关 Comments 的信息

最佳答案

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

路线.rb:

resources :comments, only: :destroy

用户 Controller :

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

评论 Controller :

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();

关于jquery - Rails 4,acts_as_commentable,删除按钮/链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22759683/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com