2016-08-24 46 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