Rails 构建评论功能(11)

2021-10-21 10:04:44 浏览数 (1)

对评论的删除加入基础认证

代码语言:javascript复制
[root@h202 blog]# vim app/controllers/comments_controller.rb 
[root@h202 blog]# cat app/controllers/comments_controller.rb 
class CommentsController < ApplicationController
###basic auth
  http_basic_authenticate_with name: "soft", password: "dog", only: :destroy
  
  def create
    @article = Article.find(params[:article_id])
    @comment = @article.comments.create(comment_params)
    redirect_to article_path(@article)
  end
 
  def destroy
    @article = Article.find(params[:article_id])
    @comment = @article.comments.find(params[:id])
    @comment.destroy
    redirect_to article_path(@article)
  end

  private
    def comment_params
      params.require(:comment).permit(:commenter, :body)
    end
end
[root@h202 blog]#  head -n 4 app/controllers/comments_controller.rb
class CommentsController < ApplicationController
###basic auth
  http_basic_authenticate_with name: "soft", password: "dog", only: :destroy
  
[root@h202 blog]# 

这时直接添加或修改文章和删除评论都会触发认证

致此,一个可以进行文章增删改查,增减评论,又有基本认证的简单博客系统就搭建起来了

虽然这只是一个小小的demo,但不得不说,ruby on rails 的开发效率是很高效的,原因是大部分本来需要手动完成的事情,这个框架已经帮忙自动完成了,我们需要做的只剩下去填补最基本的对象定义,逻辑关系,展示方式

这个流程是绝大多数管理后台的开发过程,使用rails,竟然只用两篇博客就讲清楚了


命令汇总

  • ruby -v
  • gem -v
  • rails --version
  • node -v
  • rvm -v
  • rails server -b 0.0.0.0
  • rails --help
  • rails generate model Comment commenter:string body:text
  • rails destroy model Comment
  • rails generate model Comment commenter:string body:text article:references
  • cat db/migrate/20160427082552_create_comments.rb
  • cat app/models/comment.rb
  • cat test/models/comment_test.rb
  • cat test/fixtures/comments.yml
  • rake db:migrate
  • cat app/models/article.rb
  • vim config/routes.rb
  • grep -v " #" config/routes.rb | grep -v "^$"
  • rails generate controller Comments
  • cat app/controllers/comments_controller.rb
  • cat app/views/comments
  • cat test/controllers/comments_controller_test.rb
  • cat app/helpers/comments_helper.rb
  • cat app/assets/javascripts/comments.coffee
  • cat app/assets/stylesheets/comments.scss
  • cat app/views/articles/show.html.erb
  • cat app/controllers/comments_controller.rb
  • cat app/views/articles/show.html.erb
  • cat app/views/comments/_comment.html.erb
  • cat app/views/articles/show.html.erb
  • cat app/views/comments/_form.html.erb
  • cat app/views/articles/show.html.erb
  • cat app/views/comments/_comment.html.erb
  • cat app/controllers/comments_controller.rb
  • cat app/models/article.rb
  • cat app/controllers/articles_controller.rb
  • head -n 4 app/controllers/articles_controller.rb
  • cat app/controllers/comments_controller.rb
  • head -n 4 app/controllers/comments_controller.rb

原文地址

0 人点赞