Rails rails 路由中的 member 和 collection 有何区别?

string2020 · July 30, 2014 · Last by kissyid replied at July 30, 2014 · 4123 hits

在 config/routes.rb 文件中写如下代码:

resource :topic do

member do get 'aaa' end

collection do get 'bbb' end

end

执行 rake routes aaa_topic GET /topic/aaa(.:format) topics#aaa bbb_topic GET /topic/bbb(.:format) topics#bbb

发现生成的路由竟然是一模一样的,那么请问 member 和 collection 有何区别? 既然是一样的功能(添加成员路由),为什么要搞 2 个

member 是单数概念,匹配的 URL 应该是 /topic/1/aaa

#1 楼 @Justin Routing Error

No route matches [GET] "/topic/1/aaa"

你把 resource 改成 resources 就看出不同了。

#3 楼 @Justin Routing Error

No route matches [GET] "/topics/1/aaa"

生成的路由没有带 s 啊,只是交给 topics 控制器处理吧

resources :topics do
  member do
    get 'aaa'
  end
  collection do
     get 'bbb'
  end
end

曾经也因为对关键字 resource 不了解,该有s时而没写,产生过类似的错误与疑问。

推荐 Rails Routing from the Outside In

#6 楼 @Justin 问题出来了: resource :topic resources :topic 竟然不一样,而且有一个竟然不报错

我和我的小伙伴们都惊呆了!

RailsGuide 中文版:Rails 路由全解, 看完就懂了。

@huacnlee 建议把 Ruby on Rails 指南 添加到 wiki 中 :)

You need to Sign in before reply, if you don't have an account, please Sign up first.