0

我有一个控制器问题,旨在检测任务/待办事项并将其传递给视图。

在我的应用程序布局中,我有一个保留空间来呈现这些任务

<%= yield(:tasks) if content_for?(:tasks) %>

这是我在 ApplicationController 中包含的模块。它似乎无法正常工作并且content_for?(:tasks)返回错误(byebug 说)

module TaskControl
  extend ActiveSupport::Concern

  included do
    before_action :check_tasks

    def check_tasks
      if user_signed_in? and current_user.tasks.todos.any?
        # TODO : better task strategy afterwards
        view_context.provide(:tasks, 
          view_context.cell(:tasks, current_user.tasks.todos.first)
        )
      end
      view_context.content_for?(:tasks) # => false :'(
    end
  end
end

请注意,我确实检查过 byebug,

view_context.cell(:tasks, current_user.tasks.todos.first).blank? # => false, so there is something to render
4

1 回答 1

1

您的控制器是否应该负责视图的工作方式?我会说不。

使用模块/关注点来干燥查询部分而不是为产量块提供内容是有意义的。你的控制器不应该知道视图是如何构造的。

相反,您可能希望像这样构建布局:

<body>
  <%= yield :tasks %>
  <%= yield %>

  <% if @tasks %>
  <div id="tasks">
  <%= content_for(:tasks) do %>
    <%= render partial: 'tasks' %>
  <% end %>
  </div>
  <% end %>
</body>

这使控制器可以通过提供数据来设置哪些任务 - 并让您的视图使用content_fororprovide来改变表示。

<% # app/views/foo/bar.html.erb %>
<%= provide(:tasks) do %>
  <% # this overrides anything provided by default %>
  <ul>
     <li>Water cat</li>
     <li>Feed plants</li>
  </ul>
<% end %>
于 2016-04-30T17:22:26.860 回答