使用 Id 以外的属性访问 paths.rb 中的资源

发布于 2024-08-13 11:08:29 字数 531 浏览 2 评论 0原文

我的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 like
xxxx.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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

咋地 2024-08-20 11:08:30

:id 几乎可以是您想要的任何内容。因此,保持路由配置不变,并将操作从 更改为

class ChaptersControllers
  def show
    @chapter = Chapter.find(params[:id])
  end
end

(假设您要搜索的字段名为 :chapter_no

class ChaptersControllers
  def show
    @chapter = Chapter.find_by_chapter_no!(params[:id])
  end
end

另请注意:

  1. 我正在使用 bang! finder 版本(find_by_chapter_no! 而不是 find_by_chapter_no)来模拟默认的 find 行为
  2. 您正在搜索的字段应该有一个数据库索引以获得更好的性能

:id can be almost anything you want. So, leave the routing config untouched and change your action from

class ChaptersControllers
  def show
    @chapter = Chapter.find(params[:id])
  end
end

to (assuming the field you want to search for is called :chapter_no)

class ChaptersControllers
  def show
    @chapter = Chapter.find_by_chapter_no!(params[:id])
  end
end

Also note:

  1. I'm using the bang! finder version (find_by_chapter_no! instead of find_by_chapter_no) to simulate the default find behavior
  2. The field you are searching should have a database index for better performances
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文