【问题标题】:What is the right way to handle belongs_to relationships in Rails controllers? [duplicate]在 Rails 控制器中处理 belongs_to 关系的正确方法是什么? [复制]
【发布时间】:2017-11-26 12:12:04
【问题描述】:

例如,假设我有 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

【问题讨论】:

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


【解决方案1】:

我只需将author_id 传递给books#index 以过滤特定作者的书籍。

那么books#index 会这样:

def index
  @books = Book.all
  @books = @books.where(author_id: params[:author_id]) if params[:author_id]
  render json: @books
end

【讨论】:

  • 这很有意义,是处理这种情况的典型方法。它还使事情变得更简单,因为您不需要额外的嵌套路由,只需读取 ?author_id 参数的主要 /books 路由。如果有很多过滤器参数,例如author, publish_year, genre,我通常会将它们直接映射到 AR 范围,例如:github.com/plataformatec/has_scope
猜你喜欢
  • 2019-12-28
  • 2013-08-31
  • 1970-01-01
  • 2010-10-10
  • 1970-01-01
  • 2020-12-10
  • 2012-10-31
  • 1970-01-01
  • 2014-07-20
相关资源
最近更新 更多