在控制器中提供视图内容

时间:2016-04-30 15:55:07

标签: ruby-on-rails mongoid actioncontroller ruby-on-rails-5 rails-cells

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

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

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

这是我在ApplicationController中包含的模块。它似乎没有正常工作,content_for?(:tasks)返回false(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

1 个答案:

答案 0 :(得分:1)

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

使用模块/关注点来干扰查询部分但不提供yield块的内容是有意义的。您的控制器不应该了解视图的构造方式。

相反,您可能希望如此构建布局:

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

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

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

<% # 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 %>