我的目标是从嵌套的控制器Shared::ResourceController#show
中呈现一个以app/layouts/application.html.erb
作为布局的视图。
我的控制器概述如下
app/controllers
├── application_controller.rb
├── calendars_controller.rb
├── events_controller.rb
├── shared
│ ├── base_controller.rb
│ ├── resources_controller.rb
在Shared::BaseController
中,我有一个标识资源的服务。然后控制器设置一些示例变量,如@resource
(可以是日历或事件)。
我希望继承此控制器的所有内容都在app/view/layouts/application.html.erb
中呈现其视图,因此:
# app/controllers/shared/base_controller.rb
module Shared
class BaseController < ApplicationController
layout :application
end
end
# app/controllers/shared/resources_controller.rb
module Shared
class ResourcesController < BaseController
def show
render @resource
end
end
end
布局包括一个简单的yield
:
<!-- app/views/layouts/application.html.erb -->
<html>
<head></head>
<body>
<%= yield %>
</body>
</html>
并且渲染的视图渲染一些部分:
<!-- app/views/shared/calendars/_calendar.html.erb -->
<%= render partial: './calendars/calendar_sidebar', locals: { calendar: @resource } %>
<%= render partial: './calendars/calendar' %>
但是,根据日志(和外观),布局不会呈现:
Started GET "/fr/shared/eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c" for 127.0.0.1 at 2023-05-31 14:54:50 +0200
Processing by Shared::ResourcesController#show as HTML
Parameters: {"locale"=>"fr", "token"=>"[FILTERED]"}
Calendar Load (1.6ms) SELECT "calendars".* FROM "calendars" WHERE "calendars"."id" = $1 LIMIT $2 [["id", "ef12946f-de9f-4884-88d1-d9013786cf3c"], ["LIMIT", 1]]
↳ app/services/jwt/identify_resource_service.rb:15:in `execute'
Rendered ./calendars/_calendar_sidebar.html.erb (Duration: 4.5ms | Allocations: 1192)
Rendered ./calendars/_calendar.html.erb (Duration: 0.4ms | Allocations: 116)
Rendered shared/calendars/_calendar.html.erb (Duration: 8.4ms | Allocations: 1974)
Completed 200 OK in 25ms (Views: 12.7ms | ActiveRecord: 1.6ms | Allocations: 3955)
我很确定我的控制器结构出了问题。在此之前,我的具体控制器(每事件,日历,...),一切都很好。现在我想要一些与资源无关的控制器,我无法呈现适当的布局。
问题是,如何使用嵌套控制器来构造布局?如何从控制器B::B渲染布局A?
app/view
├── A.html.rb
app/controllers
├── B
│ ├── B.rb
1条答案
按热度按时间7uhlpewt1#
render @resource
是render partial: @resource.class.name.underscore, object: @resource
的简写。也就是说,它正在做一个部分渲染(从ActionView),而不是一个控制器渲染。也就是说,没有使用布局。您需要将其更改为类似
render :some_view
的东西,它实际上应该是:show
视图,但可以是您喜欢的任何视图,但它需要是一个普通(非局部)视图,然后在其中呈现局部视图。