dimanche 26 novembre 2017

What is the right way to handle belongs_to relationships in Rails controllers?

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?

Aucun commentaire:

Enregistrer un commentaire