项目是生成好了,貌似自己还没写一句代码呢,rails把工作全给我做了,这就遇到个问题,他都给我配置了什么东西,我如果需要改一个地方的话,会不会对其他地方有影响从而发生错误呢,相信这是每一个新手都有的疑问,想到这就两眼一抹瞎,不知道怎么办了,怎么才能理清楚到底是怎么回事,我心想,那就看他代码去吧,看能不能把整个项目流程跟着代码走一遍,恩,说干咱就干。

1.new

首先我们通过url访问我们的项目,http://localhost:3000/students,这个请求到WEBrick服务器里它会怎么响应呢。不清楚啊,不过咱还是知道他最后是通过路由表找到相应的路径的,那咱就去路由表文件看看吧。Demo5/config/routes.rb

Demo5::Application.routes.draw doresources :students# The priority is based upon order of creation: first created -> highest priority.# See how all your routes lay out with "rake routes".# You can have the root of your site routed with "root"# root 'welcome#index'# Example of regular route:#   get 'products/:id' => 'catalog#view'# Example of named route that can be invoked with purchase_url(id: product.id)#   get 'products/:id/purchase' => 'catalog#purchase', as: :purchase# Example resource route (maps HTTP verbs to controller actions automatically):#   resources :products# Example resource route with options:#   resources :products do#     member do#       get 'short'#       post 'toggle'#     end##     collection do#       get 'sold'#     end#   end# Example resource route with sub-resources:#   resources :products do#     resources :comments, :sales#     resource :seller#   end# Example resource route with more complex sub-resources:#   resources :products do#     resources :comments#     resources :sales do#       get 'recent', on: :collection#     end#   end# Example resource route with concerns:#   concern :toggleable do#     post 'toggle'#   end#   resources :posts, concerns: :toggleable#   resources :photos, concerns: :toggleable# Example resource route within a namespace:#   namespace :admin do#     # Directs /admin/products/* to Admin::ProductsController#     # (app/controllers/admin/products_controller.rb)#     resources :products#   end
end

貌似只给我加了一个resources :students,这个路由它会去找哪个controller,从而响应那个view呢,恩,这是个问题,去看源码去,找controllers目录下有个students_controller,很显然这个请求交给这个controller处理了,Demo5/app/controllers/students_controller.rb,恩,就是他,代码是这样的

class StudentsController < ApplicationControllerbefore_action :set_student, only: [:show, :edit, :update, :destroy]# GET /students# GET /students.jsondef index@students = Student.allend# GET /students/1# GET /students/1.jsondef showend# GET /students/newdef new@student = Student.newend# GET /students/1/editdef editend# POST /students# POST /students.jsondef create@student = Student.new(student_params)respond_to do |format|if @student.saveformat.html { redirect_to @student, notice: 'Student was successfully created.' }format.json { render action: 'show', status: :created, location: @student }elseformat.html { render action: 'new' }format.json { render json: @student.errors, status: :unprocessable_entity }endendend# PATCH/PUT /students/1# PATCH/PUT /students/1.jsondef updaterespond_to do |format|if @student.update(student_params)format.html { redirect_to @student, notice: 'Student was successfully updated.' }format.json { head :no_content }elseformat.html { render action: 'edit' }format.json { render json: @student.errors, status: :unprocessable_entity }endendend# DELETE /students/1# DELETE /students/1.jsondef destroy@student.destroyrespond_to do |format|format.html { redirect_to students_url }format.json { head :no_content }endendprivate# Use callbacks to share common setup or constraints between actions.def set_student@student = Student.find(params[:id])end# Never trust parameters from the scary internet, only allow the white list through.def student_paramsparams.require(:student).permit(:name, :sex, :age, :phone)end
end

看到这句

# GET /students# GET /students.jsondef index@students = Student.allend

这不就是得到/students请求并作处理的一个action吗,恩,是的,这个action名字叫index,在这里定义一个变量students并初始化,我的理解Student.all是执行了一个查询的请求,把数据库students表中的数据组装成一个个的对象存在变量students里,这里students应该相当于java中的list或是map类型的吧(会是数组吗?)。总之呢,这个controller定义了一个action,用于页面跳转的,一个变量students用于存储数据的,恩,就是这样,好了,请求到这里,下面初始化好students,页面应该跳转到index页面了吧,去看看index里都有什么,Demo5/app/views/students/index.html.erb,这个文件是一个嵌入了ruby代码的html,看看去。

<h1>Listing students</h1><table><thead><tr><th>Name</th><th>Sex</th><th>Age</th><th>Phone</th><th></th><th></th><th></th></tr></thead><tbody><% @students.each do |student| %><tr><td><%= student.name %></td><td><%= student.sex %></td><td><%= student.age %></td><td><%= student.phone %></td><td><%= link_to 'Show', student %></td><td><%= link_to 'Edit', edit_student_path(student) %></td><td><%= link_to 'Destroy', student, method: :delete, data: { confirm: 'Are you sure?' } %></td></tr><% end %></tbody>
</table><br><%= link_to 'New Student', new_student_path %>

看这代码得配合着图片才有效果

相信很多人都能看懂代码啥意思了,其实细节地方我也不太懂,不过不影响咱理解他的大概意思。我们看到这个页面对数据有四种操作,增删改查,每个操作具体的交给那个action大家都明白吧,写的还是挺清楚的。下面咱就跟着链接走一遭吧,鼠标放到New Student上 ,我们看到浏览器左下角链接为localhost:3000/students/new,那就是要交给new这个action处理了,在students_controller里找到

 # GET /students/newdef new@student = Student.newend

恩,就是你了。在这里我就要说一下了,每个action都有一个相对应的xxx.html.erb,就是这个action将要跳转的页面。这里就是定义一个new的action和定义一个student的变量(应该说是对象吗,不太懂)并初始化(相当于java中的Student student = new Studen()吧),接下来就跳转到new.html.erb页面了,咱也跟着走。

看看代码去Demo5/app/views/students/new.html.erb

<h1>New student</h1><%= render 'form' %><%= link_to 'Back', students_path %>

这么简单,from就能生成一个表单吗,这个表单在哪呢,恩?view目录下有个视图文件_form.html.erb,去看看

<%= form_for(@student) do |f| %><% if @student.errors.any? %><div id="error_explanation"><h2><%= pluralize(@student.errors.count, "error") %> prohibited this student from being saved:</h2><ul><% @student.errors.full_messages.each do |msg| %><li><%= msg %></li><% end %></ul></div><% end %><div class="field"><%= f.label :name %><br><%= f.text_field :name %></div><div class="field"><%= f.label :sex %><br><%= f.text_field :sex %></div><div class="field"><%= f.label :age %><br><%= f.number_field :age %></div><div class="field"><%= f.label :phone %><br><%= f.text_field :phone %></div><div class="actions"><%= f.submit %></div>
<% end %>

这个是根据我们model的字段生成的一个form,上面是错误处理,下面就是各个字段的展示了,最后是一个action按钮,用于提交表单的,跟html挺像的是吧,我们就不研究他了,这个表单可以嵌入到别的视图代码中,不用重复写表单的代码了,这正是ruby的思想,不做重复的工作。继续我们的new student的研究,我们把new student的表单填好后,点击create student 按钮,表单被提交到create的action里了,我们去看看create这个action

 # POST /students# POST /students.jsondef create@student = Student.new(student_params)respond_to do |format|if @student.saveformat.html { redirect_to @student, notice: 'Student was successfully created.' }format.json { render action: 'show', status: :created, location: @student }elseformat.html { render action: 'new' }format.json { render json: @student.errors, status: :unprocessable_entity }endendend

拿到表单传过来的参数,初始化student,student_params是什么?传过来的参数?怎么接收的呢?看students_controller.rb

private# Use callbacks to share common setup or constraints between actions.def set_student@student = Student.find(params[:id])end# Never trust parameters from the scary internet, only allow the white list through.def student_paramsparams.require(:student).permit(:name, :sex, :age, :phone)end

这个应该相当于java中的set,get方法吧(我是这么理解的,我想应该差不多),set_student是设置student对象的,应该是初始化,注意是通过参数中的id初始化的,从这里我们想到,当我们把鼠标放到链接地址上是,url通常是localhost:3000/students/1或者是localhost:3000/students/1/edit等等,这里的1、2、3。。。应该是student的id,这样才能知道是在操作哪个student,set_student通过id从数据库中找到相应的student数据把他组装成对象(是对象吧,暂时这么理解)赋值给@studnet,@是定义变量用的。注意在students_controller开头的地方有一句

before_action :set_student, only: [:show, :edit, :update, :destroy]

这句话就是说在执行show,edit,update,destroy这些action之前先给我把student对象初始化好,这就是set_studnet存在的意义。

至于student_params的作用就不多说了吧,就像我create student,提交过来的是一个表单信息,我肯定是通过studnet_params把表单里的数据和对象里的字段对应起来,这样才能组装成一个student对象存到数据库中。

我们看到create的action定义里有一个if-else语句,这个就是说create成功我就跳到show的action里,不成功返回到new的action并带回错误信息。

2.show

其实show这个请求还是比较简单的,就是通过url请求,到达show的action,我们看到show的action的url为localhost:3000/students/1 这样就把要show那个student定义好了,前面说过了,在show之前要先执行set_student,就是通过url传过来的id从数据库中取得相应的student数据初始化好对象student,这样就能把初始化好的studnet传到view页面进行渲染了。恩,就是这样。

3.edit

edit和show差不过,就是多了一步update操作,我们看下update的action定义

 # PATCH/PUT /students/1# PATCH/PUT /students/1.jsondef updaterespond_to do |format|if @student.update(student_params)format.html { redirect_to @student, notice: 'Student was successfully updated.' }format.json { head :no_content }elseformat.html { render action: 'edit' }format.json { render json: @student.errors, status: :unprocessable_entity }endendend

if语句是对update操作成功或是失败的处理。成功就重定向到show的页面,失败就跳到edit的action里,并带回错误信息。

4.destroy

<td><%= link_to 'Destroy', student, method: :delete, data: { confirm: 'Are you sure?' } %></td>

相信大家都懂得,没啥东西,看action

# DELETE /students/1# DELETE /students/1.jsondef destroy@student.destroyrespond_to do |format|format.html { redirect_to students_url }format.json { head :no_content }endend

@student.destroy是调用destroy方法将数据库中对应的数据删除。成功后重定向到index的action里。

到这里,CRUD差不多解释完了,下面该干啥了,目标:

使用devise实现用户的注册、登录、找回密码以及修改密码。找回密码会涉及到mail配置以及发送

点击下载源码: Demo5源码

Ruby on Rails (3)相关推荐

  1. [rails] 我的订餐系统 -- 小试ruby on rails(转)

    前言         近期在java社区中一种新的脚本语言ruby,及用ruby开发的一个wab框架 rails也热闹了起来.引起了不少的java开发人员的关注. 本人平时还是很少接触脚本语言方面东东 ...

  2. ruby on rails_我成为了Ruby on Rails和React的贡献者,你也可以

    ruby on rails I am really grateful to have contributed to a few open source projects, including two ...

  3. 新手安装ruby on rails(ror)的成功必备手册

    2019独角兽企业重金招聘Python工程师标准>>> 如何快速正确的安装 Ruby, Rails 运行环境 每一位使用windows系统来进行ROR开发项目的都是这个世界上折翼的天 ...

  4. 关于 Ruby Ruby on Rails 的一些书及论坛网站

    关于 Ruby &Ruby on Rails 的一些书及论坛网站 需要用到的一些书 The Ruby Way   Programming Ruby 2nd edition Agile Web ...

  5. Ruby on Rails的下载及安装以及开发环境的搭建

    要基于ruby开发应用程序,我们必须安装ruby.gem.rails.mongrel. 第一,到官方网站上下载最新的Ruby One-Click Installer版本(已经自带了RubyGems,一 ...

  6. Ruby on Rails路径穿越与任意文件读取漏洞分析(CVE-2019-5418)

    Ruby on Rails是一个 Web 应用程序框架,是一个相对较新的 Web 应用程序框架,构建在 Ruby 语言之上.它被宣传为现有企业框架的一个替代,而它的目标,就是让 Web 开发方面的生活 ...

  7. ruby语言开源Web应用框架 Ruby on Rails 简介

    目录 Ruby on Rails是什么 历史 Rails 的 MVC 架构 Web 服务器支持 数据库支持 系统要求 集成开发环境 Ruby on Rails是什么 Ruby on Rails(官方简 ...

  8. Ruby on rails

    转自https://www.cnblogs.com/fantiantian/p/3401913.html Ruby on rails初体验(一) 接触ruby on rails 已经有一段时间了,想记 ...

  9. 安装 Ruby 和 Rails 开发环境

    最近开始学习ruby on rails,为自己的学习记录一下. 安装 系统:OS X 10.8 根据http://ruby-china.org/wiki/install_ruby_guide 安装即可 ...

  10. Ruby on rails环境和开发工具准备...

    为什么80%的码农都做不了架构师?>>>    Ruby on rails: <1>http://rubyinstaller.org/ 下载rubyinstaller(一 ...

最新文章

  1. sql按条件进行批量查询或update的关键字in
  2. Sharepoin学习笔记—架构系列—Sharepoint服务(Services)与服务应用程序框架(Service Application Framework) 2
  3. python 代码文件路径注意事项
  4. 怎样查看MySQL是否区分大小写
  5. 使用MCT6.0工具和fontconver制作MTK字库文件
  6. 码上致富(APP+H5+小程序)淘宝客APP源码导购APP源码代理淘客APP源码
  7. java 解析dataset_C# DataSet用法的详细解析|C#教程
  8. 佳博标签打印机如何打印条码流水号
  9. .Net(C#)腾讯信鸽推送
  10. 什么是Smartdrv程序
  11. WS小世界网络python快速实现——调用networkx包
  12. 5.android系统裁剪
  13. java项目 无法重命名_无法重命名数据库?
  14. 称重管理系统服务器不通,称重管理系统使用方法(二)
  15. ui设计现状与意义_UI设计存在的意义
  16. macOS Xcode8安装RVM,安装Ruby,安装/卸载Cococapods全程详解
  17. Linux - Unix环境高级编程(第三版) 代码编译
  18. uniapp | 打开iOS和Android实现GPS定位权限
  19. 牧场上的草泥马(游荡的奶牛)
  20. 京东自动抢茅台脚本(亲测可用,文末有新年礼物)

热门文章

  1. python deepcopy_python中的深拷贝(deepcopy)和浅拷贝(copy)介绍及代码参考
  2. [原创][PowerShell教程][06]PowerShell中格式化命令和输出命令
  3. PerformanceCounter 性能计数器的使用
  4. android 手机获取外置SD卡路径
  5. 使用wxcharts时,当y轴值全为0时显示错误
  6. 数据库与缓存一致性解决方案
  7. LWIP学习系列(二):STM32中ETH外设的配置与LWIP的结合使用
  8. 【BX学习之Google+】 谷歌那点事
  9. Mysql连接超时(HikariPool)
  10. 为什么A *a=new B不直接写成B b,或者B *p呢?