项目构建过程
rails new demo
创建skeletonrails generate scaffold post title:string content:text
创建post,具有如下内容:- title:string
- content:text
- timestamps(自动添加)
rails db:migrate
创建database,默认使用的是sqlite3(文件数据库)。内容参见db/schema.rb
app/views/layouts/application.html.erb
美化html文档,引入simple.min.cssapp/models/post.rb
添加Post验证,要求post.title不能为空,自动拦截不合规的请求rails action_text:install
安装富文本编辑器,rails db:migrate
再次更新数据库schema,app/models/post.rb
把富文本编辑器绑定到post.content上- 为了显示时间戳,
./bin/importmap pin local-time
添加local-time模块 (JavaScript without npm),内容参见config/importmap.rb
,可以从cdn下载或直接下载到本地发送给用户- 在
app/javascript/application.js
中引入LocalTime并初始化
- 在
app/views/posts/_post.html.erb
在post的网页模板中添加时间戳的显示位置并设计结构化显示的布局rails generate resource comment post:references content:text
添加评论功能,生成comment(resource类型),选择post作为外键(reference)rails db:migrate
再次更新数据库schema,引入commentapp/models/post.rb
在post中引入关系has_many :commentsapp/views/posts/show.html.erb
更新posts展示页面,添加post和comment展示app/views/posts/_comments.html.erb
创建comment组件,app/views/comments/_comment.html.erb
编写comment的网页模板,添加评论的内容、时间戳及其格式app/views/comments/_new.html.erb
创建new_comment组件,编写用户添加comment的网页模板app/views/posts/_post.html.erb
修改post网页模板,添加comment数量的显示app/controllers/comments_controller.rb
修改CommentsController,编写评论的创建方法(包含评论的内容非空约束)config/routes.rb
修改路由,添加评论的二级路由rails g mailer comments submitted
添加邮箱提醒功能,生成mailer,与comment的submitted事件绑定- 修改
app/mailers/comments_mailer.rb
,传入评论的参数,修改目标邮箱和邮件的标题和邮件内容模板(app/views/comments_mailer/submitted.html.erb
) - 在
app/controllers/comments_controller.rb
中的create
方法调用CommentsMailer.submitted
方法发送邮件 app/views/posts/show.html.erb
添加turbo_stream_from
,app/models/comment.rb
添加broadcasts_to
向post广播评论的增加、删除、修改操作- 运行
rails test
以发现存在的错误,修正如下app/models/post.rb
:dependent: :destroy
test/mailers/comments_mailer_test.rb
:添加传参comments(:one)
,修改assert断言部分以保持和上述修改的信息一致
项目部署过程:
- 打包docker镜像
- 修改配置
config/application.rb
config.hosts = 'host:port'
- 运行docker镜像,执行
rails server
PS:
- rubyonrails支持json格式化数据输出,在网页后缀添加
.json
即可输出json数据 - 使用
rails console
可以打开开发控制台,方便随时查看系统的数据结构、数据库的数据