Ruby On Rails博客构建

项目构建过程

  1. rails new demo创建skeleton
  2. rails generate scaffold post title:string content:text创建post,具有如下内容:
    • title:string
    • content:text
    • timestamps(自动添加)
  3. rails db:migrate创建database,默认使用的是sqlite3(文件数据库)。内容参见db/schema.rb
  4. app/views/layouts/application.html.erb美化html文档,引入simple.min.css
  5. app/models/post.rb添加Post验证,要求post.title不能为空,自动拦截不合规的请求
  6. rails action_text:install安装富文本编辑器rails db:migrate再次更新数据库schema,app/models/post.rb把富文本编辑器绑定到post.content上
  7. 为了显示时间戳,./bin/importmap pin local-time添加local-time模块 (JavaScript without npm),内容参见config/importmap.rb,可以从cdn下载或直接下载到本地发送给用户
    • app/javascript/application.js中引入LocalTime并初始化
  8. app/views/posts/_post.html.erb在post的网页模板中添加时间戳的显示位置并设计结构化显示的布局
  9. rails generate resource comment post:references content:text添加评论功能,生成comment(resource类型),选择post作为外键(reference)
  10. rails db:migrate再次更新数据库schema,引入comment
  11. app/models/post.rb在post中引入关系has_many :comments
  12. app/views/posts/show.html.erb更新posts展示页面,添加post和comment展示
  13. app/views/posts/_comments.html.erb创建comment组件,app/views/comments/_comment.html.erb编写comment的网页模板,添加评论的内容、时间戳及其格式
  14. app/views/comments/_new.html.erb创建new_comment组件,编写用户添加comment的网页模板
  15. app/views/posts/_post.html.erb修改post网页模板,添加comment数量的显示
  16. app/controllers/comments_controller.rb修改CommentsController,编写评论的创建方法(包含评论的内容非空约束)
  17. config/routes.rb修改路由,添加评论的二级路由
  18. rails g mailer comments submitted添加邮箱提醒功能,生成mailer,与comment的submitted事件绑定
  19. 修改app/mailers/comments_mailer.rb,传入评论的参数,修改目标邮箱和邮件的标题和邮件内容模板(app/views/comments_mailer/submitted.html.erb)
  20. app/controllers/comments_controller.rb中的create方法调用CommentsMailer.submitted方法发送邮件
  21. app/views/posts/show.html.erb添加turbo_stream_fromapp/models/comment.rb添加broadcasts_to向post广播评论的增加、删除、修改操作
  22. 运行rails test以发现存在的错误,修正如下
    • app/models/post.rbdependent: :destroy
    • test/mailers/comments_mailer_test.rb:添加传参comments(:one),修改assert断言部分以保持和上述修改的信息一致

项目部署过程:

  1. 打包docker镜像
  2. 修改配置config/application.rb config.hosts = 'host:port'
  3. 运行docker镜像,执行rails server

PS:

  1. rubyonrails支持json格式化数据输出,在网页后缀添加.json即可输出json数据
  2. 使用rails console可以打开开发控制台,方便随时查看系统的数据结构、数据库的数据

发表评论