2016-08-24 49 views
7

我想讓我的應用程序的實時使用Aplication.renderer.render如何從導軌5色器件

這是我的錯誤

::的ActionView ::模板錯誤(設計找不到請求環境中的Warden::Proxy實例 確保您的應用程序正在按預期方式加載Devise和Warden,並且Warden::Manager中間件存在於您的中間件堆棧中 如果您在其中一個測試中看到此項,請確保您的測試是要麼執行Rails中間件堆棧,要麼測試正在使用Devise::Test::ControllerHelpers模塊爲您注入request.env['warden']對象。)
1:-if user_signed_in?
2:.ui.popup.computer {id:「post#{post.id} user#{post.user.id}」,style:「padding:0px」}
3:.ui.card
4:圖像配

我不知道該怎麼辦

請幫助我。

+0

我還沒有找到妥善的解決辦法呢,但這裏有一些鏈接僅供參考:https://evilmartians.com/chronicles/new-feature-in-rails-5-render-views-outside-of-actions,http://www.thegreatcodeadventure.com/using-action- controller-renderers-in-rails-5-with-devise/ – artificis

回答

-1

當您使用新的Rails 5 Application Renderer時,不會執行任何中間件。 Devise使用Warden並將其設置爲環境變量env ['warden'],因此當您調用渲染器時,它就會丟失。 這就是你得到這個錯誤的原因。

爲了使它工作,在你的控制器中簡單地使用before_action作爲控制器#行動,將被渲染來設置並傳遞你需要的實例變量給視圖。

如果需要檢查,如果用戶登錄,或在渲染視圖中使用CURRENT_USER:

class ExamplesController < ApplicationController 
    before_action :user_logged_in?, only: :show 
    before_action :set_user, only: :show 

def show 
    # whatever the action does 
end 

private 
    def user_logged_in? 
    @user_logged_in = user_signed_in? 
    end 

    def set_user 
    @user = current_user 
    end 
end 

然後在視圖ExamplesController#顯示:

# views/examples/show.html.erb 

<%= "Online" if @user_logged_in %> 
<%= @user.full_name %> 

希望幫助

+0

我覺得提問者的問題來自於試圖在控制器之外呈現模板。 – artificis

0

我想我找到了適合我的案例的解決方案。

定義renderer_with_signed_in_user類方法ApplicationController

class ApplicationController < ActionController::Base 
    ... 
    def self.renderer_with_signed_in_user(user) 
    ActionController::Renderer::RACK_KEY_TRANSLATION['warden'] ||= 'warden' 
    proxy = Warden::Proxy.new({}, Warden::Manager.new({})).tap { |i| 
     i.set_user(user, scope: :user) 
    } 
    renderer.new('warden' => proxy) 
    end 
    ... 
end 

然後你就可以從Rails應用程序等部位,像這樣渲染:

renderer = ApplicationController.renderer_with_signed_in_user(user) 
renderer.render template: 'notifications/show', layout: false, locals: { foo: 'bar' } 

感謝斯特凡維納特article