0

Say, for example, that I have 2 resources Author and Book, where Author has_many Books and Book belongs_to Author.

This means that by doing the following:

# routes.rb

resources :books
resources :authors do
  resources :books
end

I will have two routes that point to BooksController#index: 1) GET /books and 2) GET /authors/:id/books.

Consider the scenario where we don't care about all the books, only the list of books from a given author (effectively putting route #1 out of use).

This leaves BooksController#index with logic that goes something like:

# BooksController.rb

def index
  @books = Book.where(author: author)
  render json: @books
end

However, the Author scoping is leaving me quite uncomfortable seeing as it is a general BooksController, where the other CRUD methods have nothing to do with Authors. Should something like the above #index method be in a separate, namespaced controller like Author::BooksController?

timorthi
  • 41
  • 1
  • 4
  • refer this question. might help you :) https://stackoverflow.com/questions/14945754/rails-nested-resources-and-routing-how-to-break-up-controllers – Vishal Taj PM Nov 26 '17 at 13:39

1 Answers1

2

I would just pass an author_id to books#index to filter the books by a specific author.

Then books#index would like this:

def index
  @books = Book.all
  @books = @books.where(author_id: params[:author_id]) if params[:author_id]
  render json: @books
end
spickermann
  • 100,941
  • 9
  • 101
  • 131
  • This makes a lot of sense and is a typical way to handle this scenario. It also keeps things simpler as you don't need additional nested routes, just the main `/books` route that reads `?author_id` param. In case there's a lot of filter params, like `author, publish_year, genre` I usually map those directly to AR scopes with something like: https://github.com/plataformatec/has_scope – tomca32 Nov 26 '17 at 15:38