我的路线如下。
map.resources :novels do |novel|
novel.resources :chapters
end
使用上面定义的路径,我可以使用
xxxxx.com/novels/:id/chapters/:id
访问章节。但这不是我想要的,章节模型有另一个名为number的字段(对应于章节号)。我想通过一个类似于
xxxx.com/novels/:novel_id/chapters/:chapter_number
如何在不显式定义命名路由的情况下完成此任务?现在,我使用在map.resources上面定义的以下命名路由来完成此任务:小说
map.chapter_no 'novels/:novel_id/chapters/:chapter_no', :controller => 'chapters', :action => 'show'
谢谢。
最佳答案
你想要什么都行。所以,保持路由配置不变,并从
class ChaptersControllers
def show
@chapter = Chapter.find(params[:id])
end
end
to(假设要搜索的字段名为
:id
)class ChaptersControllers
def show
@chapter = Chapter.find_by_chapter_no!(params[:id])
end
end
还要注意:
我在用砰的一声!finder版本(
:chapter_no
而不是find_by_chapter_no!
)模拟默认的find_by_chapter_no
行为为了获得更好的性能,您正在搜索的字段应该有一个数据库索引