Rails学习笔记(1) ————Router 路由

来源:互联网 发布:23周胎儿三维彩超数据 编辑:程序博客网 时间:2024/06/05 20:10

前言:ruby学习掌握20%就可以开始rails的学习了,知道ruby的Symbol、block和@变量即可。

1.在config的routes.rb中写上resources :students,rails会默认生成7种路由(这里假设students)

GET  /students         index     显示 student的列表页GET  /students/new     new       显示 student的新建页面GET  /students/3       show      显示id是3的studentGET  /students/3/edit  edit      显示student(id=3)的编辑页面PUT  /students/3       update    对i =3的student进行修改POST /students         create    对students进行创建DELETE  /students/3    destroy   对 id=3的 student 进行删除操作


我们这里可以在项目中敲打rake routes来查看当前项目下所有的路由:

系统输出版:

             POST     /students(.:format)             students#create  new_student GET      /students/new(.:format)         students#new edit_student GET      /students/:id/edit(.:format)    students#edit      student GET      /students/:id(.:format)         students#show             PATCH    /students/:id(.:format)         students#update             PUT      /students/:id(.:format)         students#update             DELETE   /students/:id(.:format)         students#destroy
清晰整理版:

         url       请求方式   对应的url表达式                controller#action     students_path  POST     /students(.:format)          students#create  new_student_path  GET      /students/new(.:format)         students#new edit_student_path  GET      /students/:id/edit(.:format)    students#edit      student_path  GET      /students/:id(.:format)         students#show      student_path  PATCH    /students/:id(.:format)         students#update      student_path  PUT      /students/:id(.:format)         students#update      student_path  DELETE   /students/:id(.:format)         students#student

注:url的**_path都可以换成**_url,通过url路径我们可以实现action的跳转

2.如果想额外增加自己想要增加的action怎么办呢?我们现在知道在resources :**会默认生成7中路由,我们如果单独增加,比如想增加list这个action,

我们可以这样写:

routes.rb:

resources :students do     collection do       # /students/list       get :list     endend

controller:

class StudentsController < ApplicationController   def list   endend
注:def list这个list就是action

3.实现页面的跳转

list.html.erb:

<%= link_to '添加学生信息', new_student_path %>

new.html.erb:

<%= link_to '跳转到所有学生的信息', list_students_path %>

总结:学完路由之后要能看到resources能人肉出7种路由,并能知道对应的action和url
有时间多看: 英文版:http://guides.rubyonrails.org/routing.html

                         中文版:  http://guides.ruby-china.org/routing.html


daydayup   : )


2 0
原创粉丝点击