首页
/ Acts As Commentable 技术文档

Acts As Commentable 技术文档

2024-12-23 20:34:06作者:明树来

1. 安装指南

1.1 环境要求

  • Rails 4 及以上版本。
  • 依赖于 awesome_nested_set gem,该 gem 会在安装 acts_as_commentable_with_threading 时自动安装。

1.2 安装步骤

  1. 在项目的 Gemfile 中添加以下内容:
    gem 'acts_as_commentable_with_threading'
    
  2. 运行 bundle install 命令安装 gem。

2. 项目使用说明

2.1 模型配置

在需要支持评论的模型中,添加 acts_as_commentable 方法。例如:

class Article < ActiveRecord::Base
  acts_as_commentable
end

2.2 添加评论

  • 为模型实例添加评论:

    @article = Article.find(params[:id])
    @user_who_commented = @current_user
    @comment = Comment.build_from(@article, @user_who_commented.id, "Hey guys this is my comment!")
    
  • 将新创建的评论作为另一个评论的子评论:

    @comment.move_to_child_of(the_desired_parent_comment)
    

2.3 获取评论

  • 获取某个模型实例的所有评论(包括子评论):

    @all_comments = @article.comment_threads
    
  • 获取某个模型实例的根评论(不包括子评论):

    @root_comments = @article.root_comments
    

2.4 检查评论

  • 检查某个评论是否有子评论:

    @comment.has_children?
    
  • 获取某个评论的子评论数量:

    @comment.children.size
    
  • 获取某个评论的子评论:

    @comment.children
    

3. 项目API使用文档

3.1 创建评论

  • 方法: Comment.build_from(commentable, user_id, body)
  • 参数:
    • commentable: 需要添加评论的模型实例。
    • user_id: 评论者的用户ID。
    • body: 评论内容。
  • 返回值: 新创建的评论对象。

3.2 移动评论

  • 方法: @comment.move_to_child_of(parent_comment)
  • 参数:
    • parent_comment: 目标父评论对象。
  • 返回值: 无。

3.3 获取评论

  • 方法: @article.comment_threads

  • 返回值: 包含所有评论(包括子评论)的数组。

  • 方法: @article.root_comments

  • 返回值: 仅包含根评论的数组。

3.4 检查评论

  • 方法: @comment.has_children?

  • 返回值: 布尔值,表示评论是否有子评论。

  • 方法: @comment.children.size

  • 返回值: 子评论的数量。

  • 方法: @comment.children

  • 返回值: 子评论的数组。

4. 项目安装方式

4.1 从零开始安装

  1. 生成迁移文件:
    rails generate acts_as_commentable_with_threading_migration
    
  2. 运行迁移:
    rails db:migrate
    

4.2 从 acts_as_commentable 升级

  1. 生成升级迁移文件:
    rails generate acts_as_commentable_upgrade_migration
    
  2. 运行迁移:
    rails db:migrate
    

4.3 手动创建迁移文件

如果生成器失败,可以手动创建迁移文件,参考项目中的 lib/generators 目录下的模板。

登录后查看全文
热门项目推荐
相关项目推荐