1

I have two models: Books and Chapters, where book has many chapters. I've set up the route like:

match 'book/:book_title/:chapter/:chapter_title' => 'chapter#show', :as => "chapter"

and the delegation to the Chapters controller, action show works fine.

The problem for me now is to retrieve that chapter in the show controller through the book. How this is done in case the identifiers for the query are not the primary keys?

Thanks!

lyuba
  • 6,250
  • 7
  • 27
  • 37

1 Answers1

1

You can load chapters through books like this:

@book = Book.find_by_title(params[:book_title])
@chapter = @book.chapters.find_by_title(params[:chapter_title])

Note: The find_by_* works for any database attribute on that model.

Andrew Nesbitt
  • 5,976
  • 1
  • 32
  • 36
  • I've spend a while trying to figure out why it was not working, and it turned out that the problem was in the default_scope which I'm using in the parent model. I was writing it like `default_scope where(:attribute => :value)` which resulted into wrong results with the use of the find_by_* I've changed it to `default_scope :conditions => {:attribute => :value}` and now it's working fine. Thanks! – lyuba Jul 28 '11 at 14:56