Edge Rails 的更新:RESTful 路由更新

Posted by yudi
on Monday, December 24


has_many 与 has_one 的 RESTful 路由


Rails 的路由系统可以自动分析您的 domain model 并恰当的将记录中的 ActiveRecord 脉络转化成为 RESTful 路由。现在您可以直接通过 has_one 和 has_all 来设定路由的脉络,而不是通过将资源添加到路由设定来阐释这个脉络。


map.resources :posts, :has_one => :author, :has_many => [:comments, :trackbacks]

这段代码相当于您曾经看到的下面显示:

1
2
3
4
5
map.resources :posts do |posts|
  posts.resource :author
  posts.resources :comments
  posts.resources :trackbacks
end

当然,您依然可以回到内嵌在路由设置中的列表来调整更多细节。新的方式可以使您更加直观的向路由系统表达存在于资源之间的关系。

自动设定路由名称的前缀


同一升级 里,您同样不必需要再为内嵌的资源设置名称前缀1 – 通过识别它们,Rails将为您自动假设名称前缀。比如说,在下面的路由中:

1
2
3
map.resources :posts do |posts|
  posts.resources :comments
end

现在将提供 prost_comments_url(post_id) 的 helper method。之前,您必须亲自设定名称里的 post_ 部分 以完成路由的识别:

1
2
3
map.resources :posts do |posts|
  posts.resources :comments, :name_prefix => "post_"
end

现在通过假设,这个前缀会被自动添加2。如果您不需要这个功能,则需要特别将设定为 nil: :name_prefix => nil。

噢,还请不要忘记有关路由名称的 namespace 的升级

1以此避开同其他路由的名称的分歧。

2这个假设可能会破坏您的路由定义及helper method。

原文作者是 Ryan Daigle, 请访问他的博客
本片译文的原文地址:http://ryandaigle.com/articles/2007/5/6/what-s-new-in-edge-rails-restful-routing-updates

Comments

Leave a response