新手问题 # 初学 Rails# 一点 routes

yltian · 2013年11月22日 · 最后由 yltian 回复于 2013年11月22日 · 2621 次阅读

刚开始学 rails,对 routing 部分有些疑惑,很多网上的资料由于不同的 rails 版本和中英文描述差异,看起来来很吃力。最后发现最我这种新手,最清晰反而是routes.rb注释

这是注释里routes的一些sample,我对它的理解是一些写法的分类:

  • regular route
  • named route
  • resource route
  • resource route with options
  • resource route with sub-resources
  • resource route with more complex sub-resources
  • resource route within a namespace
  • routed with "root"

他们的差别和用法我暂时没打算完全深入,先有个清晰整体的认识是现在需要的。

match 属于哪一种?

#1 楼 @lissdy 就是常规的吧,感觉这个没有带 http 动词的语义的,就是一种映射

Sample of regular route: match 'products/:id' => 'catalog#view' Keep in mind you can assign values other than :controller and :action

#1 楼 @lissdy

少用 match,它不够优雅。

#2 楼 @yltian 后面应该可以用:via 来加动词吧,比如 match 'products/:id' => 'catalog#view', :via => :get

#3 楼 @xiaoronglv 那请问哪种比较推荐,新手。嘻嘻

比较推荐 Restful……

@lissdy 不清楚。相对与这些特殊的用法,更希望搞清楚它是怎么跑起来的。Head First Ruby on Rails 58 页中讲了个流程

Behind the scenes with routes

  1. When Rails receives a request from a browser, it passes the request-path to the routes.rb to find a matching route.
  2. If the matching route contains symbols, then the Routing system will create matching parameters in the request parameters table params[...]
  3. The route can also specify additional parameters that will be inserted into params[...].:controller and :action.
  4. Once the routes.rb program has finished, Rails will look at the value of params[:controller] and use it to descide which type of controller object it needs to create.
  5. Once the controller object has been created, Rails will the use the value stored in params[:action], to choose the method within the controller to call.
  6. Then, when the controller method completes, Rails calls the page template that also matches the params[:action] value. The page template then generates the response which is sent back to the browser.

我的理解是,通过 symbols 作为占位符,去匹配请求,route 里面可以配置进去:controller 和:action。Routing system 会创建一个 params[..],这里面有请求参数和从匹配 route 中加入的:controller 和:action。顺着这个路线去找 controller 和 action

需要 登录 后方可回复, 如果你还没有账号请 注册新账号