views:

161

answers:

1

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.

+4  A: 

: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
Simone Carletti