Rails3的REST很强大了,以前我一直认为rails3无法达到django的url配置灵活度,最近仔细研究了下,发现没有啥问题,差不多麻,:-)
rails3 url配置都在 config/routes.rb中
如果刚刚生成文件,按照文件注释都可以学习很多用法,rails3的配置核心 resources 方法,这个核心很简单,看下源码就知道了,他只是自动生成一组配置,可以看作快捷方式
而对resources可以增加block来增加资源下面的配置
对于collection和member的理解很简单,collection对应所有资源,例如search等,而member中配置的为单个资源的操作,比如说订单的审核(单个资源的update)、删除等。
需要再others_controller中增加 menu1 函数,而使用
可以指定函数,这要注意的是
使用字符串这样写是指定完整的controller和action
下面要加入url变量,这个再springmvc和django都实现了,今天好奇研究了下rails3的实现
这样url=> /others/1/menu4 就会转到 others#var函数,其中中间的变量 '1'会进入params[:id]中
Next -- as函数,url好帮手
用好as函数,那么在form,a等函数中的url就可以不用配置了,如果用Rest,减少这种url把 /book?id=1
=> /book/1 喵
很简单的as函数可以在官方的文档中使用,
当然 as函数也可以加入url变量
如果配置的url中含有变量的话,调用as中指定的函数也可以加入变量,实现url配置,同事as函数也可以用于更复杂的情况
这种再view调用使用
<%= menu4_others_url(1) %>
还有些嵌套用法,namespace用法还再研究中,如果有机会的话写出来
rails3 url配置都在 config/routes.rb中
如果刚刚生成文件,按照文件注释都可以学习很多用法,rails3的配置核心 resources 方法,这个核心很简单,看下源码就知道了,他只是自动生成一组配置,可以看作快捷方式
# In Rails, a resourceful route provides a mapping between HTTP verbs
# and URLs and controller actions. By convention, each action also maps
# to particular CRUD operations in a database. A single entry in the
# routing file, such as
#
# resources :photos
#
# creates seven different routes in your application, all mapping to
# the Photos controller:
#
# GET /photos/new
# POST /photos
# GET /photos/:id
# GET /photos/:id/edit
# PUT /photos/:id
# DELETE /photos/:id
而对resources可以增加block来增加资源下面的配置
resources :others do
collection do
get 'menu1'
end
member do
end
end
对于collection和member的理解很简单,collection对应所有资源,例如search等,而member中配置的为单个资源的操作,比如说订单的审核(单个资源的update)、删除等。
get 'menu1'
需要再others_controller中增加 menu1 函数,而使用
get 'menu1' => :method_name
可以指定函数,这要注意的是
get 'menu1' => 'controller_name#action_name'
使用字符串这样写是指定完整的controller和action
下面要加入url变量,这个再springmvc和django都实现了,今天好奇研究了下rails3的实现
resources :others do
collection do
get ':id/menu4' => :var
end
end
这样url=> /others/1/menu4 就会转到 others#var函数,其中中间的变量 '1'会进入params[:id]中
Next -- as函数,url好帮手
用好as函数,那么在form,a等函数中的url就可以不用配置了,如果用Rest,减少这种url把 /book?id=1
=> /book/1 喵
很简单的as函数可以在官方的文档中使用,
# Sample of named route:
# match 'products/purchase' => 'catalog#purchase', :as => :purchase
# This route can be invoked with purchase_url
当然 as函数也可以加入url变量
# Sample of named route:
# match 'products/:id/purchase' => 'catalog#purchase', :as => :purchase
# This route can be invoked with purchase_url(:id => product.id)
如果配置的url中含有变量的话,调用as中指定的函数也可以加入变量,实现url配置,同事as函数也可以用于更复杂的情况
resources :others do
collection do
get 'menu1'
get 'menu2'
get 'menu3'
get ':id/menu4' => :var, :as=>:menu4
end
end
这种再view调用使用
<%= menu4_others_url(1) %>
还有些嵌套用法,namespace用法还再研究中,如果有机会的话写出来