0

我有一個控制器問題,旨在檢測任務/待辦事項並將其傳遞給視圖。在控制器中提供視圖內容

在我的應用程序佈局我有一個預留空間,以使這些任務

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

如果您的控制器負責視圖如何完成其工作?我會說不。

使用模塊/關注點幹查詢部分,但不提供產量塊的內容是有意義的。你的控制者不應該知道視圖是如何構建的。

相反,你可能要構建佈局像這樣:

<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 %> 
相關問題