在Rails控制器中处理belongs_to关系的正确方法是什么?

时间:2017-11-26 12:12:04

标签: ruby-on-rails ruby design-patterns

比如说,我有2个资源AuthorBook,其中Author has_many BooksBook belongs_to Author

这意味着通过执行以下操作:

# routes.rb

resources :books
resources :authors do
  resources :books
end

我将有两条指向BooksController#index的路线: 1)GET /books和2)GET /authors/:id/books

考虑我们不关心所有书籍的情况 来自特定作者的书籍清单(有效地使#1号路线无法使用)。

这使得BooksController#index的逻辑类似于:

# BooksController.rb

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

然而,Author作用范围让我感到非常不舒服,因为它是一般BooksController,其他CRUD方法与Authors无关。 上述#index方法应该在Author::BooksController之类的单独的命名空间控制器中吗?

0 个答案:

没有答案