5.2 rails routes

1. the purpose of rails routes:

 

a. recognize url, and dispatch to correct controller and actions

b. generate named routes, i.e. paths and urls, so the you needn't hardcode them in views

 

2. the simpleset route:

 

when rails receive a incoming request, 

 

GET /patients/17

 

it will ask the router to match a controller action, if the 1st match is:

 

match "/patients/:id", :to => "patients#show"

 

note, :to can be omited, so a simples way will be:

 

match "/patients/:id" => "patients#show"

 

then, the request is dispatched to patients controller, show action, with param hash {:id => "17"}


3. match "/patients/:id", :to => "patients#show"

this line of code will also create a named route (route helper):

 

so you can use it as:

 

@patient = Patient.find(17)

<%= link_to "parent 17", patient_path(@patient)%>

 the router will generate the path

/patients/17

note that you needn't metion the id in the route_helper (named route)

 

4. another important route is resourceful route for resourceful controller.

this route make you can create many good routes using just one line of code.

for example:

 

resources :photos

 

this will create many routes.

 

note that, if rails find the fisrt route that match the request, rails will not continue to search following routes.

 

5. using resourceful routes will also create some helpers (named routes) for use in views and controllers.

 

like:

photos_path,   ====> /photos

new_photo_path    ==============>/photos/new

edit_photo_path(:id)   =============> photos/17/edit

photo_path(:id)   =================> /photos/17

 

Since rails will also consider http verbs, so the four route helper map to 7 actions.

 

each of this has a corresponding _url helper.

_path is relative url

_url is full url

 

there are little difference between them.

 

6. you can define multiple resources at the same time.

 

 

resources :photo, :books, :videos
 

7. next, we talk about singular resource!!

 

for example, your client want to access profile without using id, since he is just using current login user.

 

so you can add this route:

 

match "/profile", "users#show"

 

the resource route is:

 

resource :geocoder

 

the auto-gen route helper are basically the same to plurable resources, but without id.

 

8. next is name space:

 

for example, you might want to group a group of controllers under admin, 

a. you need to put these controllers to app/controllers/admin/

 

b. in the routes file:

 

namespace :admin do

    resources :posts, :comments

end

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值