使用 Id 以外的属性访问 paths.rb 中的资源
我的routes.rb 中有以下内容
map.resources :novels do |novel|
novel.resources :chapters
end
通过上面定义的路线,我可以使用xxxxx.com/novels/:id/chapters/:id
访问章节。 但这不是我想要的,Chapter模型还有另一个名为number的字段(对应于章节号)。我想通过一个类似的 URL 访问每一章 xxxx.com/novels/:novel_id/chapters/:chapter_number
。在不显式定义命名路由的情况下如何实现此目的?
现在,我正在通过使用上面定义的以下命名路由来执行此操作。 资源:小说
map.chapter_no 'novels/:novel_id/chapters/:chapter_no', :controller => 'chapters', :action => 'show'
谢谢。
I have the following in my routes.rb
map.resources :novels do |novel|
novel.resources :chapters
end
With the above defined route, I can access the chapters by using xxxxx.com/novels/:id/chapters/:id
.
But this is not what I want, the Chapter model has another field called number (which corresponds to chapter number). I want to access each chapter through an URL which is something likexxxx.com/novels/:novel_id/chapters/:chapter_number
. How can I accomplish this without explicitly defining a named route?
Right now I'm doing this by using the following named route defined ABOVE map.resources :novels
map.chapter_no 'novels/:novel_id/chapters/:chapter_no', :controller => 'chapters', :action => 'show'
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
:id
几乎可以是您想要的任何内容。因此,保持路由配置不变,并将操作从 更改为(假设您要搜索的字段名为
:chapter_no
)另请注意:
find_by_chapter_no!
而不是find_by_chapter_no
)来模拟默认的find
行为:id
can be almost anything you want. So, leave the routing config untouched and change your action fromto (assuming the field you want to search for is called
:chapter_no
)Also note:
find_by_chapter_no!
instead offind_by_chapter_no
) to simulate the defaultfind
behavior