开发者

Accessing a resource in routes.rb by using attributes other than Id

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 c开发者_Python百科hapter 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.


: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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜