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:
- I'm using the bang! finder version (
find_by_chapter_no!
instead offind_by_chapter_no
) to simulate the defaultfind
behavior - The field you are searching should have a database index for better performances
精彩评论