Search code examples
ruby-on-railsruby-on-rails-3activerecordnested-resources

How to build an Active Recond query for the show action in the controller of the nested resource?


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!


Solution

  • 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.