我有一个名为Book
的Active Record模型和一个名为Book::Author
的模型.作者通过Book::Authorship
模型(一对多关联)拥有许多书籍.
离题:
将Author模型置于Book命名空间下的原因是,我可能希望拥有另一个与Book::Author完全无关的作者模型(例如Post::Author).通过命名空间,我可以清楚地显示关系,例如:
example.com/books/authors
明确指出这些是写书的作者(而不是帖子或其他任何东西).
在我的应用程序中,只有管理员可以创建/更新/删除书籍和作者.因此,我为控制器和仅为管理员创建了一个单独的命名空间Admin
.
在routes.rb
文件中我有:
Rails.application.routes.draw do
# These are for the regular users:
# only #index and #show actions are defined in the respective controllers:
namespace :books do
resources :authors, only: %i[index show]
end
resources :books, only: %i[index show]
# These are for the admins only:
# all CRUD methods are defined in the respective controllers:
namespace :admin do
namespace :books do
resources :authors
end
resources :books
end
resources :admin
root "books#index"
end
然后我创建了Admin::Books::AuthorsController
控制器:
/app/controllers/admin/books/authors_controller.rb
I would expect that the view path follows the same path pattern:
- 指数为
/app/views/admin/books/authors/_index.html.erb
; - 部分
/app/views/admin/books/authors/_author.html.erb
.
Unfortunately, it doesn't:索引页面确实可以工作,但找不到_author.html.erb
部分.
以下是我试图呈现/app/views/admin/books/authors/_index.html.erb
位作者列表的方式:
<% @books_authors.each do |book_author| %>
<%= render book_author %>
<% end %>
Which gives the following error:
ActionView::MissingTemplate in Admin::Books::Authors#index
缺少部分管理/books/books/作者/_作者和{.}.
There are two “books” in the path...但为什么?
works only with an explicit path to the template以上的代码:
<% @books_authors.each do |book_author| %>
<%= render "admin/books/authors/author", book_author: book_author %>
<% end %>
我不喜欢这,因为它打破了配置范式的惯例.我不想在Admin::Books::
命名空间下的每个视图中手动输入路径.
I'm looking for a way to achieve the desired functionality without using an explicit path.当Rails寻找部分内容时,我如何告诉它不要在路径中包含两次"书籍"?